if (!$.localStorage) {
	if(false  && confirm('The new version of MonkeyFly is just released.\nThere are some changes based on the HTML5 technology like below:\n\n +We reduced the process time dramatically.\n + MonkeyFly can run even if its server is down.\n\n + MonkeyFly will cut its developers\' expenses. :) \n\nThe manual update at this time is an exceptional case.\nAs usual MonkeyFly will be updated automatically.')){
		location.href='http://monkeyfly.egoing.net';
	} 
	(function($) {
		this.supported = true;
		if (typeof localStorage == 'undefined')
			this.supported = false;
		else
			var ls = localStorage;
		
		this.setItem = function(key, value, lifetime) {
			if (!this.supported)
				return false;

			ls.setItem(key, value);
		};

		this.getItem = function(key) {
			if (!this.supported)
				return false;

			return ls.getItem(key);
		};

		this.removeItem = function(key) {
			if (!this.supported)
				return false;

			ls.removeItem(key);
			return true;
		};

		$.localStorage = this;
	})(jQuery)
}

window.currentpage = $('body').attr('id');
function excludes(page){
	switch(page){
		case 'front':
		case 'create':
		case 'signup':
		case 'invitations':
		case 'settings':
		case 'login':
			return true;
	}
	return false;
}

if (!excludes(currentpage) && window.is_MonkeyFly == undefined) {

	$(document.body).addClass('monkeyfly');
	window.user = $('meta[name=session-user-screen_name]').attr('content');
    window.pageuser = $('meta[name=page-user-screen_name]').attr('content');

	window.tinyURL = 'http://api.j.mp/shorten?version=2.0.1&login=egoing&apiKey=R_644d74992a0a12588389daff443ca860';
	window.tinyType = 'bitly';
   	//var tinyURL = 'http://tinyurl.com/api-create.php?url=';
    //var tinyType = 'tinyURL';

	window.t = '/'
    window.suggestMaxInventory = 20;
    window.lastSyncInterval = 60 * 60 * 1000; //
    window.lastSync4refreshInterval = 60 * 60 * 24 * 3 * 1000; // 3일
	window.is_MonkeyFly = true;
	window.is_PBTweet = $(document.body).hasClass('pbtweet');
	
	Array.prototype.unique = function() {
		var a = [];
		var l = this.length;
		for(var i=0; i<l; i++) {
			for(var j=i+1; j<l; j++) {
				if (this[i] === this[j])
					j = ++i;
			}
			a.push(this[i]);
		}
		return a;
	};
	
	
	/*******************************************************************************************/	
	// jquery.event.wheel.js - rev 1 
	// Copyright (c) 2008, Three Dub Media (http://threedubmedia.com)
	// Liscensed under the MIT License (MIT-LICENSE.txt)
	// http://www.opensource.org/licenses/mit-license.php
	// Created: 2008-07-01 | Updated: 2008-07-14
	/*******************************************************************************************/

	// jquery method
	$.fn.wheel = function( fn ){
		return this[ fn ? "bind" : "trigger" ]( "wheel", fn );
	};

	// special event config
	$.event.special.wheel = {
		setup: function(){
			$.event.add( this, wheelEvents, wheelHandler, {} );
		},
		teardown: function(){
			$.event.remove( this, wheelEvents, wheelHandler );
		}
	};

	// events to bind ( browser sniffed... )
	var wheelEvents = !$.browser.mozilla ? "mousewheel" : // IE, opera, safari
		"DOMMouseScroll"+( $.browser.version<"1.9" ? " mousemove" : "" ); // firefox

	// shared event handler
	function wheelHandler( event ){ 
		switch ( event.type ){
		case "mousemove": // FF2 has incorrect event positions
			return $.extend( event.data, { // store the correct properties
				clientX: event.clientX, clientY: event.clientY,
				pageX: event.pageX, pageY: event.pageY
				});			
		case "DOMMouseScroll": // firefox
			$.extend( event, event.data ); // fix event properties in FF2
			event.delta = -event.detail/3; // normalize delta
			break;
		case "mousewheel": // IE, opera, safari
			event.delta = event.wheelDelta/120; // normalize delta
			if ( $.browser.opera ) event.delta *= -1; // normalize delta
			break;
		}
		event.type = "wheel"; // hijack the event	
		return $.event.handle.call( this, event, event.delta );
	};

	jQuery.fn.addTipsy = function(obj) {
		if (Setting.get('shortcut').value) {
			obj.showTimeout = 500;
			obj.additionalCSSClass = 'shortcut';
			twttr.applyTipsy($(this), '', obj);
		} else {
			var title = this.attr('title').replace(/<div.+>.+<\/div>/, '');
			if ($.trim(title) == '') {
				this.removeAttr('title');
			} else {
				this.attr('title', title);
				obj.showTimeout = 500;
				obj.additionalCSSClass = 'shortcut';
				twttr.applyTipsy($(this), '', obj);
			}
		}
	}
	
	/* DM message overwrite */

	$.fn.isCharCounter = function () {
		return this.each(function () {
			var A = true;
			var F = $(this);
			var I = F.closest("form");
			var E = I.find(".char-counter");
			var H = I.find("#tweeting_button, #update-submit, #dm-submit");
			var D = I.find("select");

			function C() {
				H.addClass("btn-disabled").attr("disabled", "disabled");
				A = true
			}

			function G() {
				if (A) {
					H.removeClass("btn-disabled").removeAttr("disabled");
					A = false
				}
			}

			function B() {
				var K = F.val();
				var J = K.length;
				if (H.attr('id') == 'dm-submit') {
					E.html(J);
					if (J <= 0 || !D.val()) {
						C()
					} else {
						G();
					}
				} else {
					E.html("" + (140 - J));
					if (J <= 0) {
						E.css("color", "#cccccc");
						C()
					} else {
						if (J <= 140 && (D.length == 0 || D.val())) {
							G()
						} else {
							C()
						}
						if (J > 130) {
							E.css("color", "#d40d12")
						} else {
							if (J > 120) {
								E.css("color", "#5c0002")
							} else {
								E.css("color", "#cccccc")
							}
						}
					}
				}
			}
			F.bind(twttr.TEXT_AREA_CHANGE_EVENTS, function (J) {
				B()
			});
			D.change(function (J) {
				B()
			});
			F.focus()
		})
	};

	$.fn.isDirectMessageForm = function() {
		return $(this).each(function () {
			var L = $(this);
			var D = L.find("textarea").isCharCounter();
			var B = /^\s*[dD][mM]?\s+([A-Za-z0-9]{1,20})[^A-Za-z0-9]/;
			var F = L.find("select");
			var A = L.find("#dm-submit");
			var E = L.find(".char-counter");
			var G = "";
			A.attr("disabled", "disabled").addClass("btn-disabled");
			try {
				D.focusEnd()
			} catch (I) {}

			function C(N) {
				if (F.val()) {
					return
				}
				if ((matches = N.match(B)) && matches[1] && (G != matches[1])) {
					var M = true;
					F.find("option").each(function () {
						if (this.innerHTML.toLowerCase() == matches[1].toLowerCase()) {
							F.val(this.value);
							M = false;
							return false
						}
					});
					if (M) {
						F.append(_('<option value="%{screen_name}">%{screen_name}</option>', {
							screen_name: matches[1]
						}));
						F.val(matches[1])
					}
					G = matches[1]
				}
			}
			A.click(function (M) {
				var P = D.val();
				var N = P.match(B);
				var O = F.find("option[value=" + F.val() + "]");
				if (N && N[1] && N[1].toLowerCase() == O.text().toLowerCase()) {
					D.val(P.replace(B, ""))
				}
				return true
			});
			F.change(function (M) {
				D.trigger("update", M)
			});
			D.bind("keyup blur focus", function (M) {
				C($(this).val());
				D.trigger("update", M)
			});

			function H(M) {
				(new ShortNotification()).setMessage(M.messageForFlash).show();
				if ($("body").attr("id") == "sent") {
					$.Timeline.prepend(M.direct_message_li)
				}
				D.val("");
				F.val("");
				G = "";
				D.trigger("change");
				E.removeClass("loading");
				if (document.all) {
					E.text("0")
				} else {
					E.css("color", "#ccc")
				}
			}
			if (F.length > 0) {
				function J() {
					if (F.length && (F.find("option").length == 0)) {
						$.ajax({
							type: "GET",
							dataType: "json",
							url: "/direct_messages/recipients_list",
							data: {
								twttr: true
							},
							success: function (N) {
								if (N) {
									var M = [];
									$.each(N, function () {
										var O = this;
										if ((O.length > 1) && O[0] && O[1]) {
											M.push('<option value="' + O[0] + '">' + O[1] + "</option>")
										}
									});
									F.html('<option value="" selected="selected"></option>' + M.join(""))
								}
							},
							error: function (M) {
								$.debug("error: " + M.responseText)
							}
						})
					}
				}
				var K = $("body").attr("id");
				if (K == "direct_messages" || K == "inbox" || K == "sent") {
					J()
				}
				L.bind("loadrecipients", null, function (M) {
					J()
				});
				L.submit(function () {
					twttr.googleAnalytics("/direct_messages/create/refresh");
					var N = D.val();
					var M = {
						authenticity_token: twttr.form_authenticity_token,
						text: N,
						"user[id]": F.val(),
						twttr: true
					};
					$.ajax({
						type: "POST",
						dataType: "json",
						url: "/direct_messages/create",
						data: M,
						beforeSend: function () {
							E.addClass("loading");
							if (document.all) {
								E.text("")
							} else {
								E.css("color", "transparent")
							}
						},
						success: H,
						error: function (O) {
							twttr.statusUpdateError.decider(O)
						}
					});
					return false
				})
			}
		})
	}
	
	/* extend Japanese i18n resources */
	
	if (page.locale == 'ja') {
		$.extend(twttr.i18n, {
			'All': '全部',
			'by others': 'みんなで',
			'by you': 'あなたで',
			'Direct Message': 'ダイレクトメッセージ',
			'Draft': '臨時保存',
			'etc...': 'その他',
			'Favorites': 'お気に入り',
			'inbox': '受信',
			'Korean spelling checker': '韓国語檢査',
			'Links': 'リンク',
			'Lists...': 'リスト...',
			'Manage %{screen_name} in your list:': 'あなたのリストで%{screen_name}を管理する:',
			'Manage in list': 'リストで管理',
			'Reply': '返事',
			'Reply all': '全員へ返信',
			'Retweets...': 'リツイート...',
			'Retweet with comment': 'コメント付RT',
			'Save': '保存する',
			'Saved keywords...': '検索メモ...',
			'sent': '送信',
			'Translate': '翻訳',
			'Tweets': 'ツイート',
			'Unfollow': 'フォローを解除',
			'URL shortener': 'URL 短縮',
			'Your tweets': 'あなたのツイート',
			'Your tweets, retweeted': 'リツイートされたあなたの',
			'yours': 'あなたの'
		});
	}
	
	var Config = {
		Layout: {
			key: 'layout_config_' + user,
			
			get: function(keypath) {
				return Config.get(Config.Layout.key, keypath);
			},
			set: function(keypath, value) {
				return Config.set(Config.Layout.key, keypath, value);
			}
		},
		Setting: {
			key: 'config_' + user,
			
			get: function(keypath) {
				return Config.get(Config.Setting.key, keypath);
			},
			set: function(keypath, value) {
				return Config.set(Config.Setting.key, keypath, value);
			}
		},
		get: function(key, keypath) {			
			var configs = Config.getAll(key);
			if (keypath) {
				var frags = keypath.split('.');

				switch (frags.length) {
				case 1:
					return configs[frags[0]];
					break;
				case 2:
					return configs[frags[0]][frags[1]];
					break;
				case 3:
					return configs[frags[0]][frags[1]][frags[2]];
					break;
				case 4:
					return configs[frags[0]][frags[1]][frags[2]][frags[3]];
					break;
				}

				return false;
			} else {
				return configs;
			}
		},
		set: function(key, keypath, value) {
			var configs = Config.getAll(key);
			if (keypath) {
				var frags = keypath.split('.');

				switch (frags.length) {
				case 1:
					configs[frags[0]] = value;
					break;
				case 2:
					configs[frags[0]][frags[1]] = value;
					break;
				case 3:
					configs[frags[0]][frags[1]][frags[2]] = value;
					break;
				case 4:
					configs[frags[0]][frags[1]][frags[2]][frags[3]] = value;
					break;
				}
			} else {
				configs = value;
			}
			
			Config.setAll(key, configs);
		},
		getAll:function(key) {
			try {
				if ($.localStorage.supported) {
					var configs = $.localStorage.getItem(key);
					if (configs)
						return JSON.parse($.localStorage.getItem(key));
					else
						return undefined;
				} else {
					return $.cookie(key);
				}
			} catch (e) {
				//console.log();
			}
		},
		setAll:function(key, value) {
			if ($.localStorage.supported)
				$.localStorage.setItem(key, JSON.stringify(value));
			else
				$.cookie(key, value, {expires:3650, path:'/'});
		}
	}
		
	/* legacy */
	if ($.localStorage && $.localStorage.supported && $.localStorage.getItem('mf_version')) {
		var old_layout = $.cookie(Config.Layout.key);

		if (old_layout) {
			$.localStorage.setItem(Config.Layout.key, old_layout);
			$.cookie(Config.Layout.key, null);
		}
		
		var old_setting = $.cookie(Config.Setting.key);

		if (old_setting) {
			$.localStorage.setItem(Config.Setting.key, old_setting);
			$.cookie(Config.Setting.key, null);
		}
	}
	
	Translate = function(){
		Translate.exec = function(text, dest, originalNest){
			if(!dest){
				if(!$('#language_box').length){
					var estr = '<select id="selectLanguage">';
					for(var name in Translate.language){
						if (name == 'UNKNOWN')
							estr+='<option value="'+Translate.language[name]+'" selected="selected">'+name+'</option>';
						else
							estr+='<option value="'+Translate.language[name]+'">'+name+'</option>';
					}
					estr+='</select>';
					var cancel = $('<button type="button" class="btn">Cancel</button>').click(Translate.cancel);
					var str = $('<div id="language_box" class="dialog"><strong>Translation Settings</strong><label for="selectLanguage">Tranlate this tweet as</label> '+estr+'<p></p></div>');
					$('p', str).append(cancel);
					
					$('body').append(str);
				}
				$('#language_box').show();
				curtain.drop(Translate.cancel);
				$('#selectLanguage').live('change', function(){
					var $this = $(this);
					if($this.val()){
						Setting.data.translate.translate_language = $this.val();
						Config.Setting.set('translate.translate_language', $this.val());
						curtain.lift();
						$('#language_box').hide();
						Translate.exec(text,$this.val(),originalNest);
					}
				})
				Translate.repaint();
				return false;
			}
			var n = $($(originalNest)[0]);
			google.load("language", "1",{'callback':
				function(){
					if(n.data('translate')) {
						var d = n.data('translate');
						d.text('Processing....');
					}else {
						var d = $('<span id="'+n.closest('.hentry').attr('id')+'Translated" class="msgtxt en translate">Processing....</span>');
						n.data('translate', d).after(d);
					}
					google.language.translate(text, '', dest, function(result) {
						if (!result.error) {
							$(d).html(text2Tweet (result.translation.replace(/# (\w+)/g,'#$1').replace(/@ (\w+)/g,'#$1'))+Translate.selectForm(dest, result.detectedSourceLanguage));
						} else {
							$(d).html('Sorry, I cant translate'+(result.detectedSourceLanguage ? Translate.selectForm(dest, result.detectedSourceLanguage) : Translate.selectForm(dest)));
						}
					})	
				}
			});
		}
		Translate.toFirstUpperCase = function(string){
			return string.charAt(0).toUpperCase()+string.substr(1).toLowerCase();
		}
		Translate.selectForm = function(selectedLang,originalLang){
			var option = '';
			var ol = '';
			var str = '<select class="translateSelect">';
			for(var name in google.language.Languages){
				if(google.language.Languages[name]==originalLang)
					ol = name+'->';
			}
			for(var name in google.language.Languages){
				if(google.language.Languages[name]==selectedLang){
				   str += '<option value="'+google.language.Languages[name]+'" selected="selected">'+Translate.toFirstUpperCase(ol)+Translate.toFirstUpperCase(name)+'</option>';
				} else
					str += '<option value="'+google.language.Languages[name]+'">'+Translate.toFirstUpperCase(ol)+Translate.toFirstUpperCase(name)+'</option>';
			}
			str+='</select>';
			return str;
		}
		Translate.cancel = function() {
			curtain.lift();
			$('#language_box').hide();
		}
		Translate.repaint = function(){
			$('#language_box').css('left', ($(window).width()/2 - $('#language_box').width()/2)+'px').css('top', ($(window).height()/2-$('#language_box').height()/2) + 'px');	
		}
		Translate.init = function() {
		
			$('span.translate select.translateSelect').live('change', function(){
				$this = $(this);
				var t = $this.closest('.hentry').find('span.entry-content');
				Translate.exec($(t[0]).text(),$this.val(), t);
				Setting.data.translate.translate_language = $this.val();
				Config.Setting.set('translate.translate_language', $this.val());
				return false;	
			})
		}
		Translate.init();
	}
	Translate.language = eval({"AFRIKAANS":"af","ALBANIAN":"sq","AMHARIC":"am","ARABIC":"ar","ARMENIAN":"hy","AZERBAIJANI":"az","BASQUE":"eu","BELARUSIAN":"be","BENGALI":"bn","BIHARI":"bh","BULGARIAN":"bg","BURMESE":"my","CATALAN":"ca","CHEROKEE":"chr","CHINESE":"zh","CHINESE_SIMPLIFIED":"zh-CN","CHINESE_TRADITIONAL":"zh-TW","CROATIAN":"hr","CZECH":"cs","DANISH":"da","DHIVEHI":"dv","DUTCH":"nl","ENGLISH":"en","ESPERANTO":"eo","ESTONIAN":"et","FILIPINO":"tl","FINNISH":"fi","FRENCH":"fr","GALICIAN":"gl","GEORGIAN":"ka","GERMAN":"de","GREEK":"el","GUARANI":"gn","GUJARATI":"gu","HEBREW":"iw","HINDI":"hi","HUNGARIAN":"hu","ICELANDIC":"is","INDONESIAN":"id","INUKTITUT":"iu","IRISH":"ga","ITALIAN":"it","JAPANESE":"ja","KANNADA":"kn","KAZAKH":"kk","KHMER":"km","KOREAN":"ko","KURDISH":"ku","KYRGYZ":"ky","LAOTHIAN":"lo","LATVIAN":"lv","LITHUANIAN":"lt","MACEDONIAN":"mk","MALAY":"ms","MALAYALAM":"ml","MALTESE":"mt","MARATHI":"mr","MONGOLIAN":"mn","NEPALI":"ne","NORWEGIAN":"no","ORIYA":"or","PASHTO":"ps","PERSIAN":"fa","POLISH":"pl","PORTUGUESE":"pt-PT","PUNJABI":"pa","ROMANIAN":"ro","RUSSIAN":"ru","SANSKRIT":"sa","SERBIAN":"sr","SINDHI":"sd","SINHALESE":"si","SLOVAK":"sk","SLOVENIAN":"sl","SPANISH":"es","SWAHILI":"sw","SWEDISH":"sv","TAJIK":"tg","TAMIL":"ta","TAGALOG":"tl","TELUGU":"te","THAI":"th","TIBETAN":"bo","TURKISH":"tr","UKRAINIAN":"uk","URDU":"ur","UZBEK":"uz","UIGHUR":"ug","VIETNAMESE":"vi","WELSH":"cy","YIDDISH":"yi","UNKNOWN":""});
	
	var Setting = {
		data: null,
		list: [
			// write
			{label:'Photo Uploader', id:'photo', init:true, category:'extend'},
			{label:'URL Shortener', id:'tinyText', init:true, category:'extend'},
			{label:'Auto Suggestion', id:'suggest', init:true, category:'extend'},
			{label:'Korean Spelling Checker', id:'koreanSpellCheck', init:false, category:'extend'},
			
			// read
			{label:'Media Preview', id:'preview', init:true, category:'extend', description:'MonkeyFly displays the preview of image and movie. This supports TwitPic, YouTube, Flickr, yfrog, TweetPhoto and img.ly.'},
			{label:'Translation', id:'translate', init:true, category:'extend', option:[
				{label:'Translate a tweet into', id:'translate_language', init:null, type:'select', element:Translate.language}
			]},
			
			// information
			{label:'Profile', id:'profile', init:true, category:'info', description:'MonkeyFly provides the Profile feature that display any tweeter\'s information without redirecting the page.'},
			{label:'Link Statistics', id:'links', init:true, category:'info', description:'MonkeyFly provides the statistics on people that have visited the link you tweeted.'},
			//{label:'Tool Tip', id:'tooltip', init:true}, Deprecated
			
			// global
			{label:'Use the Group Tab for grouping the columns', id:'gtab', init:true, category:'global'},
			{label:'Multiple Columns', id:'grid', init:true, category:'global'},
			{label:'Shortcut Access', id:'shortcut', init:true, category:'global', description:'MonkeyFly\'s features can be accessed by the keyboard.'},
			
			// customize
			{label:'CSS', id:'css', init:true, category:'customize', option:[
				{label:'description', id:'css_description', type:'textarea', init:''}
			]},
			
			// privacy
			{label:'Privacy Protection', id:'privacy', init:true, category:'privacy', option:[
				{label:'When idle, hide the direct message', id:'privacy_hide_dm', init:true, type:'checkbox'},
				{label:'When idle, hide all', id:'privacy_hide_all', init:false, type:'checkbox'},
				{label:'Idle time (sec)', id:'privacy_interval', init:60*5, type:'text'}
			]}
		],
		get: function(name) {
			try {
				var D = null;
				try {
					D = Config.Setting.get();
				} catch(e) {}
				if (D == null || D[name] == null) {
					for (var i=0; i<Setting.list.length; i++) {
						if (Setting.list[i].id == name) {
							var c = Setting.list[i];
							if (c.id == name) {
								var E = {value:c.init};
								for (var _name in c.option) {
									var _c = c.option[_name];
									E[_c.id] = _c.init;
								}
								return E;
							}
							break;
						}
					}
				} else {
					return D[name];
				}
			} catch(e){
				console.log(e);
			}
			return {value:null}
		}
	}
	
	function Dialog() {
		this.$super = this.prototype;
		this.__construct();
	}
	
	jQuery.extend(Dialog.prototype, {
		$super: null,
		id: null,
		container: null,
		
		__construct: function() {
			this.$super = Dialog.prototype;
		},
		open: function() {
			curtain.drop(this.close.pBind(this));
			
			if ($('#' + this.id).length) {
				this.container.trigger('reset');
				this.container.show();
			} else {
				this.create();
				$('body').append(this.container);
				$(window).resize(this.repaint());
			}
			
			this.repaint();
		},
		close: function() {
			this.container.hide();
			curtain.lift();
		},
		repaint: function() {
			this.container.css({top: ($(window).height() - this.container.height()) / 2 + 'px', left: ($(window).width() - this.container.width()) / 2 + 'px'});
		}
	});
	
	function DialogSettings() {
		this.__construct();
	};
	DialogSettings.prototype = new Dialog();

	jQuery.extend(DialogSettings.prototype, {
		id: 'settingPanel',
		prefix: 'user_monkeyfly_',
		tabs: null,
		chks: {},
		rows: null,
		template: '<tr class="%{category}">\
				<th><label for="%{id}">%{label}</label></th>\
				<td>%{content}</td>\
			</tr>',
		
		__construct: function() {
			$('#home_link').ready(function () {
				var monkeyfly = $('<li> <a id="monkeyFlySetting" href="http://monkeyfly.egoing.net/" target="_blank">MonkeyFly</a></li>');
				$('#home_link').parent().after(monkeyfly);
				$('#monkeyFlySetting', monkeyfly).click(function(event){
					this.open();
					$('#global_tab', this.container).trigger('click');
					
					this.rows.hide();
					this.container.find('tr.global').show();
					this.repaint();
					
					event.preventDefault();
				}.pBind(this));
			}.pBind(this));
			
			Setting.data = {};
			
			for (var i=0; i<Setting.list.length; i++) {
				Setting.data[Setting.list[i].id] = {value:Setting.list[i].init};
				
				if (Setting.list[i].label)
					Setting.data[Setting.list[i].id].label = Setting.list[i].label;
			}
			
			if (Config.Setting.get()) {
				var _d = Config.Setting.get();
				for (var name in _d)
					Setting.data[name] = _d[name];
			}
		},
		create: function() {
			var str = '<form id="%{id}" class="dialog" action="post">\
					<div class="title">MonkeyFly settings</div>\
					<ul class="nav">\
						<li><a href="#" id="global_tab">Global</a></li>\
						<li><a href="#" id="extend_tab">Outer Rim</a></li>\
						<li><a href="#" id="info_tab">Information</a></li>\
						<li><a href="#" id="customize_tab">customize</a></li>\
						<li><a href="#" id="privacy_tab">Privacy</a></li>\
					</ul>\
					<fieldset>\
						<table class="input-form">\
							<tbody>%{content}</tbody>\
						</table>\
					</fieldset>\
					<div class="buttons">\
						<input type="submit" id="monkeyfly_settings_save" class="btn btn-m" name="commit" value="' + _('Save') + '" />\
						<input type="button" id="monkeyfly_settings_cancel" class="btn btn-m" name="commit" value="' + _('Cancel') + '" />\
					</div>\
				</form>';
			
			var content = '';
			
			for (var i=0; i<Setting.list.length; i++)
				content += this._createRow(Setting.list[i]);
			
			str = replaceParams(str, {id:this.id, content:content});
			
			this.container = $(str);
			this.tabs = $('ul.nav li', this.container);
			this.rows = $('tr', this.container);
			this.chks.grid = $('#' + this.prefix + 'grid', this.container);
			this.chks.gtab = $('#' + this.prefix + 'gtab', this.container);
			this.chks.translate = $('#' + this.prefix + 'translate', this.container);
			this.chks.language = $('#' + this.prefix + 'translate_translate_language', this.container);
			this.chks.css = $('#' + this.prefix + 'css', this.container);
			this.chks.textarea = $('textarea', this.container);
			this.chks.privacy = $('#' + this.prefix + 'privacy', this.container);
			
			this.checkGridChkbox(this.chks.grid);
			this.checkTranslationChkbox(this.chks.translate);
			this.checkCSSChkbox(this.chks.css);
			this.checkPrivacyChkbox(this.chks.privacy);
			
			$('ul li a', this.container).click(function(event) {
				var target = $(event.target);
				this.tabs.removeClass('active');
				target.parent('li').addClass('active');
				this.rows.hide();
				this.container.find('tr.' + target.attr('id').replace('_tab', '')).show();
			}.pBind(this));
			
			this.chks.grid.click(function(event) {
				this.checkGridChkbox(event.target);
			}.pBind(this));
			
			this.chks.translate.click(function(event) {
				this.checkTranslationChkbox(event.target);
			}.pBind(this))
			
			this.chks.css.click(function(event) {
				this.checkCSSChkbox(event.target);
			}.pBind(this));
			
			this.chks.privacy.click(function(event) {
				this.checkPrivacyChkbox(event.target);
			}.pBind(this));
			
			$('#monkeyfly_settings_save', this.container).click(function(event) {
				this.save();
				//event.preventDefault();
				//event.stopPropagation();
				return false;
			}.pBind(this));
			$('#monkeyfly_settings_cancel', this.container).click(function(event) {
				this.container.trigger('reset');
				this.close();
				//event.preventDefault();
				//event.stopPropagation();
				return false;
			}.pBind(this));
		},
		checkGridChkbox: function(target) {
			this.chks.gtab.attr('disabled', !$(target).is(':checked'));
		},
		checkCSSChkbox: function(target) {
			this.chks.textarea.attr('disabled', !$(target).is(':checked'));
		},
		checkTranslationChkbox: function(target) {
			this.chks.language.attr('disabled', !$(target).is(':checked'));
		},
		checkPrivacyChkbox: function(target) {
			$('tr.privacy ul input', this.container).attr('disabled', !$(target).is(':checked'));
		},
		save: function() {
			try {
				var data = {};
				var c = null;
				var subs = null;
				
				for (var i=0; i<Setting.list.length; i++) {
					c = Setting.list[i];
					if (data[c.id] == null)
						data[c.id] = {};
					
					data[c.id].value = $(':checkbox[name='+c.id+']').is(':checked');
					
					if (c.option != undefined) {
						subs = c.option;
						for (var j=0; j<subs.length; j++) {
							switch (subs[j].type) {
							case 'checkbox':
								data[c.id][subs[j].id] = !!$('#' + this.prefix + c.id + '_' + subs[j].id).attr('checked');
								break;
							default:
								data[c.id][subs[j].id] = $('#' + this.prefix + c.id + '_' + subs[j].id).val();
								break;
							}
						}
					}
				}
				
				Config.Setting.set('', data);
				Setting.data = data;
				location.reload();
			} catch(e) {
				//console.log(e);
			}
		},
		_createRow: function(c) {
			var id = this.prefix + c.id;
			var chkbox = this._designElement(c, id, Setting.get(c.id).value == undefined ? c.init : Setting.get(c.id).value) + this._designLabel(id, 'activate');
			var content = '';
			
			switch (c.id) {
			case 'translate':
				var s = c.option[0];
				content = this._designLabel(id+'_'+s.id, s.label) + this._designElement(s, id+'_'+s.id, Setting.get(c.id)[s.id] == undefined ? '' : Setting.get(c.id)[s.id]);
				
				break;
			case 'css':
				var s = c.option[0];
				content = this._designElement(s, id+'_'+s.id, Setting.get(c.id)[s.id] == undefined ? '' : Setting.get(c.id)[s.id]);
				
				break;
			case 'grid':
				var s = Setting.list[8];
				content = this._designElement(s, this.prefix+s.id, Setting.get(s.id).value == undefined ? s.init : Setting.get(s.id).value) + this._designLabel(this.prefix+s.id, s.label);
				
				break;
			case 'gtab':
				return '';
				break;
			case 'privacy':
				var s = null;
				content = '<ul>';
				for (var i=0; i<c.option.length; i++) {
					s = c.option[i];
					
					if (s.type == 'text')
						content += '<li>' + this._designLabel(id+'_'+s.id, s.label) + this._designElement(s, id + '_' + s.id, Setting.get(c.id)[s.id] == undefined ? 300 : Setting.get(c.id)[s.id]) + '</li>';
					else
						content += '<li>' + this._designElement(s, id+'_'+s.id, Setting.get(c.id)[s.id] == undefined ? 'true' : Setting.get(c.id)[s.id]) + this._designLabel(id+'_'+s.id, s.label) + '</li>';
				}
				content += '</ul>';
				
				break;
			}
			
			if (!!content) 
				content = '<div class="sub">' + content + '</div>';
			else if (c.description)
				content = '<div class="sub">' + c.description + '</div>';
			
			var str = replaceParams(this.template, {id:id, label:c.label, category:c.category, content:chkbox+content});
			
			return str;
		},
		_designLabel: function(id, text) {
			return '<label for="' + id + '">' + text + '</label>';
		},
		_designElement: function(c, id, value) {
			var element = null;
			if (!c.type) c.type = 'checkbox';
			
			switch (c.type) {
			case 'checkbox':
				element = '<input type="checkbox" id="' + id + '" name="' + c.id + '" value="true"'+ (value ? ' checked="checked"' : '') + ' />';
				break;
			case 'text':
				element = '<input type="text" id="' + id + '" name="' + c.id + '" value="' + value + '" />';
				break;
			case 'select':
				var element = '<select id="' + id + '" name="' + c.id + '">';
				for (var name in c.element)
					element += '<option value="' + c.element[name] + '"' + (value == c.element[name] ? ' selected="selected"' : '') + '>' + name + '</option>';
				element += '</select>';
				break;
			case 'textarea':
				element = '<textarea id="' + id + '" name="' + c.id + '">' + value + '</textarea>';
				break;
			}
			
			return element;
		}
	});
	
	new DialogSettings();

    function insertPhoto(photo) {
        var target = '#status';
        if ($('body').attr('id') == 'direct_messages') {
            target = '#direct_message_form #text';
        }
        $(target).val($(target).val() + photo);
    }

    function login(service, desc, feedback, flag) {
		try{
			if(!flag)
				popup('profile', 'show');
			var profileSession = getMovieName('profileSession');
			profileSession.login(service, desc, feedback ? true : false);
		}catch(e){
			console.log(1);
			setTimeout('login("'+service+'","'+desc+'","'+feedback+'",true)',1000);
		}
	}

    function onLoginComplete(e) {
        switch (e.target) {
        case 'twitpic':
            try {
                popup('profile', 'hide');
                var movie = getMovieName('twitpic');
                for (i = 0; i < movie.length; i++) {
                    try {
                        movie[i].run();
                    } catch(e) {
                        console.log(e);
                    }
                }
            } catch(e) {
                console.log(e);
            }
            break;
        }

    }

    function popup(target, mode) {
        switch (target) {
        case 'profile':
            if (mode == 'show') {
                $('#status_login_box').addClass('show');
                curtain.drop();
            } else {
                $('#status_login_box').removeClass('show');
				curtain.lift();
            }
            break;
        case 'externalWindow':
            if (mode == 'show') {
                $('#externalWindow').addClass('show');
            } else {
                $('#externalWindow').removeClass('show');
            }
        }
    }

    function getMovieName(movieName) {
        if (navigator.appName.indexOf("Microsoft") != -1) {
            return window[movieName]
        } else {
            return document[movieName]
        }
    }
/* Deprecate
	(function($){
		$.fajax=function(obj){
			var frequest = getMovieName('fhttpRequest');
			$.fajax.list.push(obj);
			var index = $.fajax.list.length-1;
			//$.fajax.callback(index,obj);
			frequest.ajax({type:'POST', url:encodeURIComponent(obj.url), data:obj.data, id:index, callback:'$.fajax.callback'});
		}
		$.fajax.callback = function(id,obj){
			$.fajax.list[id].success(obj.data);
		}
		$.fajax.list = new Array();
	})(jQuery)
*/
	function ScreenCurtain() {
		this.__construct();
	}
	
	jQuery.extend(ScreenCurtain.prototype, {
		mask: null,
		
		__construct: function() {
			this.mask = $('<div id="mask"></div>');
			
			this.mask.wheel(function(event) {
				event.stopPropagation();
				event.preventDefault();
			});
			
			$(document.body).append(this.mask.hide());
		},
		lift: function() {
			this.mask.hide().css('cursor', 'default').unbind('click');
			$('#twitpic').show();
		},
		drop: function(fn) {
			this.mask.show();
			$('#twitpic').hide();
			if (fn)
				this.mask.css('cursor', 'pointer').click(fn);
		}
	});

	function Friends() {
        var popular = 0;
        var self = this;
        Friends.fi = null;
        Friends.flag = true;
        Friends.lastSyncDate = null;
        this.getValue = function (callback) {
            if (Friends.fi == undefined) {
                try {
                    Friends.lastSyncDate = $.localStorage.getItem('lastSyncDate')
                    Friends.fi = eval($.localStorage.getItem('following'));
                    var l = Friends.lastSyncDate;
                    var c = ((new Date()).getTime());
                    var i = window.lastSync4refreshInterval;

                    if (l != null && l + i < c) {
                        if (Friends.flag) {
                            Friends.sync(callback);
                        }
                        Friends.flag = false;
                        return Friends.fi;
                    }

                } catch(e) {
                    return[];
                }
                if (Friends.fi == null) {
                    var l = Friends.lastSyncDate;
                    var c = ((new Date()).getTime());
                    var i = window.lastSyncInterval;

                    if (l != null && l + i > c) {
                        return[];
                    }
                    if (Friends.flag) Friends.sync(callback);
                    Friends.flag = false;
                }
            }
            return Friends.fi;
        }
        this.setValue = function (name, value) {
			$.localStorage.setItem(name,JSON.stringify(value),5000)
        }
        this.popularity = function (username, additionalScore) {
            var d = self.getValue();
            for (var i = 0; i < d.length; i++) {
                if (d[i].username == username) {
                    if (Friends.fi[i].popularity == undefined) Friends.fi[i].popularity = 0;
                    Friends.fi[i].popularity = (Friends.fi[i].popularity + additionalScore);

                    this.sort();
                    return;
                }
            }
        }
        this.sortMan = function (a, b) {
            if (a.popularity < b.popularity) {
                return 1;
            } else {
                return -1;
            }
        }
        this.sort = function () {
            var d = self.getValue();
            d.sort(self.sortMan);
            this.setValue('following', d);
            //getValue();
        }

		Friends.getRelation = function(targetUsername, callback){
			if(Friends.getRelation.comm != undefined){
				Friends.getRelation.comm.abort();
			}

			Friends.getRelation.comm = $.ajax({
				type: "GET",
				url: '/'+targetUsername,
				dataType:'html/text',
				success: function (html) {
					try {
						var pStatus = /<div id="user_(\d+)" class="user (following|blocking)?\s?(direct-messageable)?"/;
						var status = html.match(pStatus);
						relation = 'none';
						if(status[3] != undefined && status[3] == 'direct-messageable'){
							if(status[2] == 'following'){
								relation = 'friend';
							} else {
								relation = 'follower';
							}
						} else if(status[2] == 'following'){
							relation = 'following';
						}

						callback(relation);
					} catch(e) {
						if(html.indexOf('id="cancel_request"')>-1){
							callback('requested_protected');
						} else if(html.indexOf('id="send_request"')>-1){
							callback('protected');
						} else {
							callback('nothing');
						}

					}
				}
			});
		}

		Friends.create = function(targetusername,callback){
			if(Friends.create.comm != undefined){
				Friends.create.comm.abort();
			}
			Friends.create.comm = $.ajax({
				type: "POST",
                dataType: "json",
                url: "/friendships/create/" + targetusername,
                data: {
                    authenticity_token: twttr.form_authenticity_token,
                    twttr: true
                },
                success: function (J) {
                    callback(J)
                }
			});
		}

		Friends.destroy = function(targetusername,callback){
			if(Friends.destroy.comm != undefined){
				Friends.destroy.comm.abort();
			}
			Friends.destroy.comm = $.ajax({
                type: "POST",
                dataType: "json",
                url: "/friendships/destroy/" + targetusername,
                data: {
                    authenticity_token: twttr.form_authenticity_token,
                    twttr: true
                },
                success: function (J) {
                    callback(J);
                }
            });
		}


        Friends.sync = function (callback, id) {
            var lists = new Array();
            if (this.comm != undefined) this.comm.abort();
            this.comm = $.ajax({
                type: "GET",
                url: "/following" + (id == null ? '' : '?page=' + id),
                success: function (html) {
                    window._data = html;
                    var ctime = (new Date()).getTime();
					$.localStorage.setItem('lastSyncDate',ctime);
                    Friends.lastSyncDate = ctime;
                    var td = html.match(/(<td class="user-detail">[\s\S]+?<\/td>)/mg);
                    if(Friends.fi == undefined){
						Friends.fi = new Array();	
					}
					for (i = 0; i < td.length; i++) {
                        try {
                            var screenname = td[i].match(/<span class="label fullname">([\s\S]+?)<\/span>/m);
                        } catch(e) {
                            console.log(e);
                        }
                        try {
                            var username = td[i].match(/<a href[\s\S]+title="(\w+)"[\s\S]*?<\/a>/m);
                        } catch(e) {
                            console.log(e);
                        }
                        try {
                            var u = username != null ? username[1] : '';
                            var s = screenname != null ? screenname[1] : '';
                            var skip = false;
							for(var k=0; k< Friends.fi.length; k++){
								if(Friends.fi[k].username == u) {
									skip = true;
									break;
								}
							}
							if(skip){
								continue;
							}
							lists.push({
                                username: u,
                                screenname: s,
                                popularity: popular++
                            });
                        } catch(e) {
                            console.log(e);
                        }
                    }
                    try {
                        if (Friends.fi == null) {
                            Friends.fi = lists;
                        } else {
                            for (var i = 0; i < lists.length; i++) {
                                Friends.fi.push(lists[i]);
                            }
                        }
						$.localStorage.setItem('following',JSON.stringify(Friends.fi));
                        if (callback != undefined) {
                            callback(Friends.fi);
                        }
                    } catch(e) {
                        console.log(e);
                    }
                    try {
                        var page = $(html).find('#pagination a').attr('href').match(/page=(\d+)/)[1];
						if (page == null) {
                            return;
                        } else {
                            Friends.sync(null, page);
                        }
                    } catch(e) {
						console.log(e);
                    }
                }
            });
        }
    } // end of Friends
	
	

    function Suggest(parent, input, listeners) {
        var parent = parent;
        this.input = input;
        var position = 0;
        var length = 0;
        var active = false;
        this.keyIgnore = false;
        this.keyIgnorePattern = /\W/;
        var currentData = new Array();
        var _listeners = listeners;
		var $root;
        Suggest.id = 0;
        this.id = 0;
        var self = this;
        (function init() {
            $(parent).ready(function () {
                id = ++Suggest.id;
                $(parent).prepend('<div style="-moz-user-select: none; display:none;" class="suggest" role="listbox" id="monkey_suggest' + id + '"></div>');
            	$root = $('#monkey_suggest'+id);
			});
            $('#monkey_suggest' + id + ' .element').livequery('mouseover', function () {
               	var $this = $(this);
				self.focus(Number($this.attr('index'))+1);
            }).livequery('mouseout', function () {
                $(this).removeClass('selected');
            }).livequery('click', function () {
                position = Number($(this).attr('index')) + 1;
                self.select();
                self.hide();
            });

        })()
        this.items = function (data) {
            var str = '';
            position = 1;
            currentData = data;
            for (var i = 0; i < data.length; i++) {
                length = i;
                var m = data[i].matching;
                var _m = m.toLowerCase();
                var _d = data[i].username.toLowerCase();
                var u = '<b class="ac-highlighted" style="-moz-user-select: none;">' + data[i].username.substr(0, m.length) + '</b>' + data[i].username.substr(m.length);
                if(data[i].screenname.length>0){
					var s = ' &lt;' + data[i].screenname + '&gt;';
				} else {
					var s = '';
				}
				str += '\
				<div role="option" index="' + i + '" class="element' + (i == 0 ? ' selected' : '') + '" style="-moz-user-select: none;" username="' + data[i].username + '" matching="' + data[i].matching + '" screenname="' + data[i].screenname + '" front="' + encodeURI(data[i].front) + '" back="' + encodeURI(data[i].back) + '">\
					<div class="aq" style="-moz-user-select: none;">\
					  <div class="al" style="-moz-user-select: none;">\
						<div class="ak de" style="-moz-user-select: none;"/>\
					  </div>\
					  <div class="am" style="-moz-user-select: none;">@' + u + s +'</div>\
					</div>\
				</div>';
            }
            $('#monkey_suggest' + id).show();
			$('#monkey_suggest' + id).css('left', $('#status').position().left+'px').css('top', ($('#status').position().top+$('#status').height()+10)+'px');
            active = true;
            $('#monkey_suggest' + id).html(str);
        }

		$(input).livequery('keydown',function (event) {
			listeners(event,{type:'keydown',target:self});
		}).livequery('keypress',function (event) {
			listeners(event,{type:'keypress',target:self});
		}).livequery('keyup',function (event) {
			listeners(event,{type:'keyup',target:self});
        });
        this.hide = function () {
            if (!active) return true;
            active = false;
            $('#monkey_suggest' + id).hide();
        }
        this.isActive = function () {
            return active;
        }
        this.select = function () {
            var t = $('#monkey_suggest' + id + ' div.element:nth-child(' + (position) + ')');
			return listeners(new Object(), {
                type: 'selected',
                target: self,
                selected: {
                    username: t.attr('username'),
                    screenname: t.attr('screenname'),
                    matching: t.attr('matching'),
                    back: t.attr('back'),
                    front: t.attr('front')
                }
            });
        }
		this.focus = function(_position){
			position = Math.min(Math.max(_position, 1), length+1);
			$('#monkey_suggest' + id + ' div.element').removeClass('selected');
            var t = $('#monkey_suggest' + id + ' div.element:nth-child(' + position + ')');
			t.addClass('selected');
			try{
				var username = $(t[0]).attr('username');
				var offset = $root.offset();
			} catch(e) {
				console.log(e);
			}
		}
        this.up = function () {
            this.focus(position-1)
        }
        this.down = function () {
			this.focus(position+1)
        }
    }

	/*
	ascii code
	8 	: back space
	13 	: enter
	38 	: up
	40	: down
	*/
    function suggetsListener(event, obj) {
        suggetsListener.atReg = /@\w{0,}$/;

        switch (obj.type) {
        case 'keydown':
            _k = event.keyCode;
			switch (_k) {
            case 13:
                if (!obj.target.isActive()) return;
                var s = obj.target.select();
                if (obj.target.isActive) event.preventDefault();
                break;
            case 38:
                if (!obj.target.isActive()) return;
                obj.target.up();
                obj.target.keyIgnore = true;
                event.preventDefault();
                return;
            case 40:
                if (!obj.target.isActive()) return;
                obj.target.down();
                obj.target.keyIgnore = true;
                event.preventDefault();
                return;
            }
            obj.target.keyIgnore = false;
            obj.target.keyIgnore = obj.target.keyIgnorePattern.test(String.fromCharCode(_k));
            switch (_k) {
            case 229:
                // click
            case 21:
                //한영키
            case 16:
                //쉬프트
                return;
            case 8:
                obj.target.keyIgnore = false;
                return;
            }
            if (obj.target.keyIgnore) {
                obj.target.hide();
                obj.target.keyIgnore = true;
                return;
            }
            break;
        case 'keypress':
            break;
        case 'keyup':
            _k = event.keyCode;
            text = $(obj.target.input).val();
            if (text.indexOf('@') == -1) {
                obj.target.hide();
                return;
            }
			switch(_k){
				case 229: // click
				case 21: //한영키
				case 16: //쉬프트
					return;
			}
			if(obj.target.keyIgnore) {
				switch(_k){ // 위,아래 방향키에서는 suggest를 끄지 않음
					case 38: // up
					case 40: // down
					return;
				}
				obj.target.hide();
				return;
			}


            selection = $(obj.target.input).getSelection();
            front = text.substring(0, selection.end);
            back = text.substring(selection.end, text.length);
            var result = front.match(suggetsListener.atReg);
            if (result == null) {
                obj.target.hide();
                return;
            }

            f = fri.getValue();
            if (f == null) {
                obj.target.hide();
                return;
            }

            var elem = new Array();
			for (var i = 0; i < f.length; i++) {
                if (elem.length >= window.suggestMaxInventory) break;
                
				var username = f[i].username;
                var screenname = f[i].screenname;
                var matching = result[0].substr(1);
                var _matching = matching;
                if (username.toLowerCase().indexOf(_matching.toLowerCase()) == 0) {
                    elem.push({
                        username: username,
                        matching: matching,
                        screenname: screenname,
                        front: front,
                        back: back
                    });
                }
            }
            if (elem.length > 0) {
                obj.target.items(elem);
            } else if (elem.length == 0) {
                obj.target.hide();
            }
            break;
        case 'selected':
            var s = obj.selected;
            var f = decodeURI(s.front);
            var b = decodeURI(s.back);
            f = f.substr(0, f.lastIndexOf('@')) + '@' + s.username + ' ';
            //f.replace(/@.{0,}$/,'@'+s.username+' ');
            b = b.replace(/\w/, '');
            $('#status').val(f + b);
            obj.target.hide();
            fri.popularity(s.username, 10000);
            obj.target.keyIgnore = true;
            $('#status').focus();
			break;

        }
    }

    (function () {
        var fieldSelection = {
            getSelection: function () {
                var e = this.jquery ? this[0] : this;
                return (
                /* mozilla / dom 3.0 */
                ('selectionStart' in e &&
                function () {
                    var l = e.selectionEnd - e.selectionStart;
                    return {
                        start: e.selectionStart,
                        end: e.selectionEnd,
                        length: l,
                        text: e.value.substr(e.selectionStart, l)
                    };
                }) ||
                /* exploder */
                (document.selection &&
                function () {
                    e.focus();
                    var r = document.selection.createRange();
                    if (r == null) {
                        return {
                            start: 0,
                            end: e.value.length,
                            length: 0
                        }
                    }
                    var re = e.createTextRange();
                    var rc = re.duplicate();
                    re.moveToBookmark(r.getBookmark());
                    rc.setEndPoint('EndToStart', re);
                    return {
                        start: rc.text.length,
                        end: rc.text.length + r.text.length,
                        length: r.text.length,
                        text: r.text
                    };
                }) ||
                /* browser not supported */
                function () {
                    return {
                        start: 0,
                        end: e.value.length,
                        length: 0
                    };
                }

                )();
            },
            replaceSelection: function () {
                var e = this.jquery ? this[0] : this;
                var text = arguments[0] || '';
                return (
                /* mozilla / dom 3.0 */
                ('selectionStart' in e &&
                function () {
                    e.value = e.value.substr(0, e.selectionStart) + text + e.value.substr(e.selectionEnd, e.value.length);
                    return this;
                }) ||
                /* exploder */
                (document.selection &&
                function () {
                    e.focus();
                    document.selection.createRange().text = text;
                    return this;
                }) ||
                /* browser not supported */
                function () {
                    e.value += text;
                    return this;
                }

                )();

            }

        };

        jQuery.each(fieldSelection, function (i) {
            jQuery.fn[i] = this;
        });

    })();


	(function($) {
		$.fn.watch = function(propertyName, callbackMethod) {
			for (var i = 0; i < this.length; i++) {
				var o = this[i];
				//if (o.watch)
				//	o.watch(propertyName, callbackMethod); //pass to built in watch handler JS 1.5
				//else if (watchIt)
					watchIt(o, propertyName, callbackMethod); //use timer based watch/check
			}
		}
		//if (typeof (Object.prototype.watch) == "undefined") {
			var watchedObjects = [];
			$(checkWatches);
			function checkWatches() {
				try {
					var x;
					for (var i = 0; i < watchedObjects.length; i++) {
						x = watchedObjects[i];
						if (x.obj[x.prop] != x.last || typeof (x.obj[x.prop]) != typeof (x.last)) {
							x.exec.call(x.obj, x.prop, x.last, x.obj[x.prop]);
							x.last = x.obj[x.prop];
						}
					}
				} catch (err) {

				}
				watchTimer = window.setTimeout(checkWatches, 500);
			}
			function watchIt(obj, propertyName, callbackMethod) {
				watchedObjects.push({
					"obj": obj,
					"prop": propertyName,
					"last": obj[propertyName],
					"exec": callbackMethod
				});
			}
		//}
	})(jQuery);

    $(document.body).ready(function () {
		fri = new Friends();
		var _data = eval($.localStorage.getItem('following'));
		if (_data == undefined) {
			Friends.sync();
		} else {
			window.friendsInfo = _data;
		}
		if(Setting.get('suggest').value){
			sugg = new Suggest('div.info', '#status', suggetsListener);
		}
    });
	
	var legacyFcookie = '';
	
	{ // 플래쉬 쿠키를 로컬 캐쉬로 변경하면서 임시적으로 구현한 마이그레이션을 위한 레거시 코드. 2011년에는 삭제해도 무방할 것으로 예상됨.
		function checkfcookie(){
			if(getMovieName('fcookie')&&getMovieName('fcookie').getValue){
				fcookie = getMovieName('fcookie');
				var p = fcookie.getValue('draft');
				var p = p ? p : [];
				$.localStorage.setItem('draft', JSON.stringify(p));
				$.localStorage.setItem('links',  JSON.stringify(fcookie.getValue('links')));
				console.log(fcookie.getValue('links'));

			} else {
				setTimeout('checkfcookie()', 1000);	
			}
		}
		if(!$.localStorage.getItem('draft') || !$.localStorage.getItem('links')){
			legacyFcookie = '<embed class="hidden_flash" src="' + srcURL + 'cookie.swf?' + seed + '" quality="high" bgcolor="#ffffff" width="1" height="1" name="fcookie" id="fcookie" flashvars="&id=' + user + '" align="middle" allowScriptAccess="always" allowFullScreen="false" scaleMode="noScale" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" wmode="transparent" style="left:0;position:fixed;top:0;"/>';
			checkfcookie();
		} 
	}
	
    $(document.body).prepend(legacyFcookie);
	
	var curtain = new ScreenCurtain();

	var friends = $('#direct_message_user_id').html();

	var new_db_update_box = $('<div id="dm_update_box">\
		<form action="/direct_messages" class="status-update-form" id="direct_message_form" method="post">\
			<input name="authenticity_token" type="hidden" value="2ba19ff72589bee7728880e4cc7ddca3feac8d2e">\
			\
			<fieldset class="common-form standard-form">\
				<div class="bar">\
					<h3><label for="doing">Send <select name="user[id]" id="direct_message_user_id" accesskey="&gt;" tabindex="3"></select> a direct message.</label></h3>\
					<span id="chars_left_notice" class="numeric"><strong id="status-field-char-counter" class="char-counter" style="color: rgb(204, 204, 204); ">0</strong></span>\
				</div>\
				<div class="info">\
					<div style="-moz-user-select: none; display:none;" class="suggest" role="listbox" id="monkey_suggest1"></div>\
					<div id="status_progress" style="background-color: white; height: 5px; margin-bottom: 2px; display: block !important; width: 520px !important; ">\
						<div class="progress_bar" style="background-color:rgba(82, 168, 236, 0); height:100%; width:0"></div>\
					</div>\
					<textarea accesskey="u" autocomplete="off" cols="15" id="text" name="text" rows="3" tabindex="4" style="height: 90px; "></textarea>\
				</div>\
				<div class="status-btn">\
					<input type="submit" name="update" value="send" id="dm-submit" class="round-btn dm-btn btn-disabled" tabindex="4" disabled="">\
					<input id="direct_message_screen_name" name="screen_name" type="hidden" value="">\
					<input id="tab_action" name="tab" type="hidden" value="index">\
				</div>\
			</fieldset>\
		</form>\
	</div>');

	$('#direct_message_user_id', new_db_update_box).html(friends);
	new_db_update_box.isDirectMessageForm();
	$('#dm_update_box').replaceWith(new_db_update_box);
	
	if(Setting.get('tinyText').value){
		$('div#tweeting_controls,#dm_update_box .status-btn').prepend(' <a tabindex="4" class="a-btn a-btn-m tinyTextSubmit" id="tinyTextSubmit" name="update">' + _('URL shortener') + '</a>');
	}
	if(Setting.get('koreanSpellCheck').value){
		$('div#tweeting_controls,#dm_update_box .status-btn').prepend(' <a tabindex="5" class="a-btn a-btn-m spellcheckSubmit" id="spellcheckSubmit" name="update">' + _('Korean spelling checker') + '</a>');
		$(document.body).append('<form id="spellcheck_form" target="externalContentHolder" action="' + srcURL + 'control.php?mode=spellCheck" method="POST">' + '	<input id="spellcheck_content" type="hidden" name="data"></input>' + '</form><div id="command_view"></div>');
	}
    if(Setting.get('photo').value){
    	$(document.body).append('<div id="status_login_box" class="dialog"><embed src="' + srcURL + 'profile.swf?' + seed + '" quality="high" bgcolor="#ffffff" width="100%" height="100%" name="profileSession" id="profileSession" flashvars="&id=' + user + '" allowScriptAccess="always" allowFullScreen="true" scaleMode="noScale" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" /></div>');
		$('div#tweeting_controls').prepend('<embed src="' + srcURL + 'twitpic.swf" flashvars=&id=' + user + '&url=' + srcURL + '&' + seed + '" quality="high" bgcolor="#ffffff" width="70" height="26" name="twitpic" id="twitpic" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" style="margin-top:-2px; vertical-align:middle;" />');
		$('#dm_update_box .status-btn').prepend('<embed src="' + srcURL + 'twitpic.swf" flashvars=&id=' + user + '&url=' + srcURL + '&' + seed + '" quality="high" bgcolor="#ffffff" width="70" height="26" name="twitpic" id="twitpic" allowScriptAccess="always" wmode="opaque" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" style="margin-top:-2px; vertical-align:middle;" />');
		
		$('.info #status').before($('\
			<div id="status_progress" style="background-color: white; height: 5px; margin-bottom:2px;display:block !important; width:520px !important;">\
				<div class="progress_bar" style="background-color:rgba(82, 168, 236, 0); height:100%; width:0"></div>\
			</div>').css('width', $('#status').width()+6+'px').hide()).bind("blur focus change " + ($.browser.mozilla ? "paste input" : "keyup"),function(){
			var $this = $(this);
			var c = $this.val().length;
			$('#status-field-char-counter').text(140-c);
			var p = $this.parents('#direct_message_form').length>0 ? '#direct_message_form' : '#status_update_form';
			$(p+' #status_progress .progress_bar').css('width',  Math.min(100,Math.ceil(100 * c/140))+'%').css('background-color','rgba(82, 168, 236, '+(0.2+0.4* c/140)+')');
		})
	}

    if(Setting.get('css').value){
		$('head').append('<style type="text/css">'+Setting.get('css').css_description+'</style>');
	}

	function Draft(){
		Draft.repaint = function(){
			p = eval($.localStorage.getItem('draft'));
			p = p ? p : [];
			var str = '<div id="draft_nest" class="draft_nest"><ol class="statuses draft" id="timeline">';
			var m = ['Jan','Feb','Mar','Apr','May','June', 'Jul', 'Aug','Sep', 'Oct','Nov', 'Dec']
			for(var i = p.length-1 ; i >= 0; i--){
				var d = new Date(p[i].date);
				var t = (d.getHours()%12)+':'+d.getMinutes()+' '+(d.getHours()>12 ? 'PM' : 'AM')+' '+m[d.getMonth()]+' '+d.getDate()+'th';
				c = p[i].value.replace(/@(\w+)/g,'<a href="/$1" class="tweet-url username">@$1</a>').replace(/#(\w+)/g,'<a class="tweet-url hashtag" title="#$1" href="/search?q=%23$1">#$1</a>').replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,"<a href=\"$1\" target=\"_blank\">$1</a>");
				str += '\
						<li  class="hentry mine status">\
    						<span class="status-body">\
              				<span class="entry-content">'+c+'</span>\
        					<span class="meta entry-meta">\
  								<a rel="bookmark" class="entry-date">\
    								<span class="published timestamp">'+t+'</span>\
  								</a>\
    						<ul class="actions-hover">\
								<li>\
						  			<span class="use">\
										<a title="update this tweet" href="#" index="'+p[i].date+'">Use</a>\
						  			</span>\
									<span class="delete">\
										<a title="delete this tweet" href="#" index="'+p[i].date+'">Delete</a>\
						  			</span>\
								</li>\
					  		</ul>\
					  	</span>\
					</li>';
			}
			str += '</ol><a rel="next" class="round more" id="draft_close">' + _('Close') + '</a></div>';
			$('.draft_nest').remove();
			$('#tweeting_controls, #dm_update_box .status-btn').after(str);
			$('.statuses.draft').css('visibility', p.length == 0 ? 'hidden' : 'visible');
			if(p.length == 0) {$('#draft_nest').hide()} else {$('#draft_nest').show()}

		}
		Draft.init = function(){
			$('#tweeting_button').before(' <a tabindex="3" class="a-btn a-btn-m draft" id="draft" name="draft">' + _('Draft') + '</a> ');
			$('#dm-submit').before(' <a type="submit" tabindex="2" class="a-btn a-btn-m draft" id="draft">' + _('Draft') + '</a> ');
			$('.draft').click(function(){
				var t = ($('body').attr('id') == 'inbox' || $('body').attr('id') == 'sent') ? $('textarea#text') : $('textarea#status');
				var p = eval($.localStorage.getItem('draft'));
				if(t[0].value.length>0){
					var d = (new Date()).getTime();
					var v = t[0].value;
					var m = ($('body').attr('id') == 'inbox' || $('body').attr('id') == 'sent') ? 1 : 0;
					if(p == undefined){
						p = [];
					}
					p.push({value:v, date:d, mode:m});
					$.localStorage.setItem('draft', JSON.stringify(p));
					var t = ($('body').attr('id') == 'inbox' || $('body').attr('id') == 'sent') ? $('textarea#text') : $('textarea#status');
					t[0].value = '';
				}
				Draft.repaint();
				return false;
			})
			$('.statuses.draft span.delete a').live('click',function(){
				if(confirm('Really?')){
					$this = $(this);
					Draft.cut($(this).attr('index'));
					Draft.repaint();
				}
				return false;
			})
			$('.statuses.draft span.use a').live('click',function(){
				var t = ($('body').attr('id') == 'inbox' || $('body').attr('id') == 'sent') ? $('textarea#text') : $('textarea#status');
				
				t[0].value = (Draft.cut($(this).attr('index'))).value;
				Draft.repaint();
			})
			$('#draft_close').live('click', function(){
				$('.draft_nest').remove();
			})
		}
		Draft.cut = function(index){
			var p = eval($.localStorage.getItem('draft'));
			for(var i = 0 ; i < p.length; i++){
				if(index == p[i].date){
					var d = p[i];
					p.splice(i,1);
					$.localStorage.setItem('draft', JSON.stringify(p));
					return d;
				}
			}
		}
		Draft.init();
	}
	Draft();
	
	function Links() {		
		//setTimeout(function() {
			this.__construct(0);
		//}.pBind(this), 100);
	}
	
	Links.data = [];
	Links.add = function(obj) {
		try {
			if(Links.data!=undefined){
				for(var i = 0 ; i < Links.data.length; i++){
					if(Links.data[i].tinyURL == obj.tinyURL){
						return;
					}
				}
				Links.data.unshift(obj);
			} else {
				Links.data = new Array();
				Links.data.unshift(obj);
			}
			$.localStorage.setItem('links', JSON.stringify(Links.data));
		} catch(e) {
			console.log(e);
		}
	}
	
	$.extend(Links.prototype, {
		pageScale: 20,
		
		_page: 0,
		_primary: null,
		_link: null, 
		_pagination: null,
		_timeline: null,
		_buffer: {pagination:null},
		
		__construct: function(i) {
			var i = i == undefined ? 0 : i;
			if (eval($.localStorage.getItem('links')) == null) {
				if (i < 20) {
					setTimeout(function() {
						this.__construct(++i);
					}.pBind(this), 500);
				}
				
				return false;
			} else {
				Links.data = eval($.localStorage.getItem('links'));
			}
			
			this._primary = $('#primary_nav');
			this._pagination = $($('#pagination')[0]);
			this._return = $('<a id="return-home" href="#">return Home</a>');
			$('#heading #return-home').live('click', this.deactivate.pBind(this));
			
			if (!!Links.data && !!Links.data.length) {
				$('#favorites_tab', this._primary).after(' <li id="links_tab"><a>' + _('Links') + '</span></li>');
				this._link = $('#links_tab', this._primary).click(function(event) {
					this.activate();
					event.preventDefault();
					event.stopPropagation();
				}.pBind(this));
			}
			$('#home_tab .in-page-link', this._primary).click(function(event) {
				var parent = $(event.target).closest('li');
				$('#timeline_heading').children('a:first').hide();
				this.addReturnHome(parent, true);
			}.pBind(this));
			$('#replies_tab .in-page-link, #direct_messages_tab .in-page-link', this._primary).click(function(event) {
				var parent = $(event.target).closest('li');
				$('#timeline_heading').children('a:first').hide();
				this.addReturnHome(parent, false);
			}.pBind(this));
			$('#favorites_tab .in-page-link', this._primary).click(function(event) {
				var parent = $(event.target).closest('li');
				$('#timeline_heading').children('a:first').hide();
				this.addReturnHome(parent, false);
			}.pBind(this));
			
			$('body.grid #retweet_tabs a').each(function(i, obj) {
				switch(i) {
				case 0:
					$(obj).text(_('by others'));
					break;
				case 1:
					$(obj).text(_('by you'));
					break;
				case 2:
					$(obj).text(_('yours'));
					break;
				}
			})
			
			$('#retweets_by_others_tab .in-page-link', this._primary).click(function(event) {
				var parent = $(event.target).closest('li');
				$('#timeline_heading').children('a:first').hide();
				this.addReturnHome(parent, false, function() {
					$('#heading').text('Retweets');
				});
			}.pBind(this));
		},
		addReturnHome: function(target, home, fn) {
			var timer = setInterval(function() {
				if (!target.hasClass('loading')) {
					$('#heading').css('display', home ? 'inline-block' : 'block');
					if (home) {
						$(document.body).append(this._return.hide());
						$('#timeline_heading').children('a:first').show();
					} else {
						if ($.isFunction(fn)) fn();
						$('#timeline_heading h1').append(this._return.show());
						$('#timeline_heading').children('a').hide();
						
					}
					clearInterval(timer);
				}
			}.pBind(this), 300);
		},
		removeReturnHome: function() {
			$('#heading').css('display', 'inline-block');
			$(document.body).append(this._return.hide());
		},
		activate: function() {
			this._page = 0;
			this._timeline = $($('#timeline')[0]);
			this._buffer.pagination = this._pagination.html();
			this._pagination.html('<a rel="next" id="more" href="#" class="round more">' + _('more') + '</a>');
			this._timeline.html('');

			$('.more', this._pagination).click(this.loadLinks.pBind(this));
			$(document.body).attr('id', 'links');
			$('li', this._primary).removeClass('active');
			this._link.addClass('active');
			$('#timeline_heading h1').text('Links');
			$('#timeline_heading').children('a').hide();
			this.addReturnHome(this._link, false);
			this.loadLinks();
		},
		deactivate: function() {
			this._timeline.html('');
			this.removeReturnHome();
			$('#home_tab a').trigger('click');
		},
		loadLinks: function() {
			var max_elem = Math.min((this._page+1) * this.pageScale, Links.data.length);
			
			var str = '';
			for (var i=this._page*this.pageScale; i<max_elem; i++) {
				str += '<li class="list_list status" index="'+i+'" tinyURL="'+Links.data[i].tinyURL+'">\
							<span class="body">\
								<span class="title"><a class="hentry status search_result" href="'+Links.data[i].tinyURL+'" target="_blank">'+(Links.data[i].original).substr(0,65)+'</a></span>\
								<span class="tiny">alias '+Links.data[i].tinyURL+'</span>\
								<span class="clicks"></span>\
							</span>\
					</li>';
			}
			
			this._timeline.append(str);
			this.stat();
			this._page++;
			
			if (Links.data.length == max_elem)
				this._pagination.remove();
			
			return false;
		},
		stat: function() {
			$('li.list_list[index]', this._timeline).each(function(i, obj){
				var target = $(obj);
				var index = target.attr('index');
				target.removeAttr('index');
				
				try{
					$.getJSON('http://api.bit.ly/stats?version=2.0.1&shortUrl='+Links.data[index].tinyURL+'&login=egoing&apiKey=R_644d74992a0a12588389daff443ca860&callback=?',function(data){
						target.find('.clicks').html(' <a href="'+target.attr('tinyURL')+'+" target="_blank">(clicks:'+(data.results.clicks == undefined ? 0 : data.results.clicks)+')</a>');
					})
				} catch(e){
					console.log(e);
				}
				
				if (!Links.data[index].htmlTitle) {
					$.getJSON('http://api.bit.ly/info?version=2.0.1&shortUrl='+Links.data[index].tinyURL+'&login=egoing&apiKey=R_644d74992a0a12588389daff443ca860&callback=?', function(data){
						var m = $(target).attr('tinyURL').match(/http:\/\/.+?\/(.+)/);
						if (!!m && m.length > 1) {
							var htmlTitle = data.results[m[1]]['htmlTitle'];
							if(htmlTitle != '') {
								Links.data[index].htmlTitle = htmlTitle;
								$.localStorage.setItem('links', JSON.stringify(Links.data));
								target.find('.title a').html(htmlTitle);
							}
						}
					});
				} else {
					$(target).find('.title a').html(Links.data[index]['htmlTitle']);
				}
			});
		}
	});
	
	if(Setting.get('links').value){
		linksObj = new Links();
	}
	
	function DragAndDrop() {
		this.__construct()
	}
	
	$.extend(DragAndDrop.prototype, {
		_dragMode: false,
		_target: null,
		_dummy: null,
		_fn: null,
		_timer: null,
		_timeoutInMilliseconds: 0,
		_notification: null,
		
		__construct: function() {
			$(document).mousemove(function(event) {
				this.isDragging(event);
			}.pBind(this)).mouseup(function(event) {
				this.drop(event);
			}.pBind(this));
			
			this._notification = new InfoNotification();
			this._notification.timeoutInMilliseconds = 999999999;
		},
		seize: function(event, target, parent, selector, id, fn) {
			this._timer = setTimeout(function() {
				this._selector = selector;
				this._target = $(target).closest(selector);
				this._index = this._target.parent().find(selector).index(this._target);
				this._target.visible(false);
				this._dummy = $('<div>'+this._target.html()+'<div class="layer"> </div></div>').attr('className', this._target.attr('className')).css({
					top:this._target.offset().top + 'px',
					left:this._target.offset().left + 'px',
					width:this._target.width() + 'px'
				});
				$(document.body).append(this._dummy);

				if (id) this._dummy.attr('id', id);
				if (fn) this._fn = fn;

				this.resetSiblings();
				this.base_x = this._target.offset().left;
				this.previous_x = event.pageX;
				this.prev_x = this.base_x + event.pageX - this.previous_x;
				this._index = $(parent).find(selector).index(this._target);
				this._min = $(parent).find(selector + ':first').offset().left;
				this._max = $(parent).find(selector + ':last').offset().left + $(parent).find(selector + ':last').outerWidth();
				this._dragMode = true;
			}.pBind(this), 200);
			
			event.preventDefault();
			event.stopPropagation();
		},
		isDragging: function(event) {
			if (this._dragMode) {
				var left = this.base_x + event.pageX - this.previous_x;

				switch (this.getDirection(left)) {
				case '-':
					if (!!this._prev && this._prev.length) {
						var center = this._prev.offset().left + Math.floor(this._prev.outerWidth() / 2);
						if (left <= center) {
							this._prev.before(this._target);
							this.resetSiblings();
						}
					}
					break;
				case '+':
					var right = left + this._dummy.outerWidth();
					if (!!this._next && this._next.length) {
						var center = this._next.offset().left + Math.floor(this._next.outerWidth() / 2);
						if (right >= center) {
							this._next.after(this._target);
							this.resetSiblings();
						}
					}
					if (right >= this._max)
						left = this._max - this._dummy.outerWidth();
					break;
				}

				if (left < this._min)
					left = this._min;

				this._dummy.css('left', left + 'px');

				event.preventDefault();
				event.stopPropagation();
			}
		},
		drop: function(event) {
			clearTimeout(this._timer);
			this._dragMode = false;
			this._timer = null;
			
			if (!!this._target && this._target.length)
				this._target.visible(true);
			
			if (this._fn && !!this._target && this._index != this._target.parent().find(this._selector).index(this._target)) this._fn();
			this._target = null;
			
			if (!!this._dummy && $(this._dummy, 'body').length)
				this._dummy.remove();
			
			event.preventDefault();
			event.stopPropagation();
		},
		getDirection: function(left) {
			var mark = '';
			if (this.prev_x == undefined)
				mark = '0';
			else if (this.prev_x < left)
				mark = '+';
			else if (this.prev_x > left)
				mark = '-';
			this.prev_x = left;
			return mark
		},
		resetSiblings: function() {
			this._prev = this._target.prev(this._selector);
			this._next = this._target.next(this._selector);
		}
	});
	
	dragndrop = new DragAndDrop();
	
	function Tab(config){
		Tab.config = config;
		Tab.$tabMenuNest = null;
		
		Tab.init = function(){
			var tabstr = '\
			<div id="globalTab">\
				<ul id="tabControl" class="control">\
					<li><a id="tab_refresh" href="#" title="Refresh all columns<div class=\'shortcut\'>Shortcut key: a as in Anakin</div>"><img src="data: image/png;base64, iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHsSURBVDjLtZPpTlpRFIV5Dt7AOESr1kYNThGnSomIihPoNVi5Qp3RgBgvEERpRW1BRBAcMEDUtIkdjKk4otK0Jdr2vgxZ3kA0MYoaG3+cX2evb529zt4sAKz/OawnASgCBNm5LaE7vjVDutkA4mMdLV4TkvcCuvba2Iqd1pDhWA33mQU+2oXVv07YfpoxuNWFuqVXoeqFCnZcgJwRm04p+Gk3Fs9t8PyZx/K5Hfbf03CGLRj62g2+rSR0K0D+vZXUB1Xw/ou5usJWjAaU0Gz3w/rjHey/ZjDLvKTD34KSyXzyBkC2JaYd4feMqyNa3OQTREQePlXjrqSq5ssj5hMjTMd66ALDKDLm0jcA0s+NID6JIFmvQaNXANEKX3l5x7NyqTcb7Zg8GYtCOLoXuPcbha6XV0VlU4WUzE9gPKjF2CGFbE3G3QAmafDnShETF3iKTZyIblcNza4Syi/deD6USscFCJwV6Fwn8NonQak5Hy1L9TAcjkJ/oAG1p0a1hYdnfcnkrQCBoxyyNYLp1YCJoB7GIwqGgxGod/oZsQoNDiHSepNCceeAN8uF1CvGxJE25rofc+3blKPqQ2VUnKxIYN85yty3eWh216LeKUTOSCayVGlIH0g5S+1JJB+8Cxxt1rWkH7WNTNIPAlwA9Gm7OcXUHxUAAAAASUVORK5CYII=" alt="" /></a></li><li><a id="tab_add" href="#"><img src=""></a></li><li><a id="tab_minus" href="#"><img src="" title="remove this tab"></a></li>\
				</ul>\
				<ul style="display: block;" id="tabMenuNest" class="tabMenu global">';
			for(var i = 0, _i = Tab.config.tabs.length; i < _i ; i++){
				tabstr+=Tab.template(Tab.config.tabs[i].label,Tab.config.tabs[i].index,Tab.config.tabs[i].index == Tab.config.tabsActive?true:false, i+1);
			}
			tabstr +='</ul>\
			</div>';
			var globalTabNest = $('#content div.wrapper div.section');
			$($(globalTabNest)[globalTabNest.length-1]).before(tabstr);
			
			Tab.$tabMenuNest = $('#tabMenuNest');
			Tab.$tabMenuNest.find('li a:first').each(function(i, obj) {
				$(obj).addTipsy({gravity:'s'});
			});
			Tab.change(Tab.config.tabsActive);
			$('#tab_add').click(function(){
				var label = prompt('Group tab\'s name?');
				if(label)
					Tab.add(label);
				this.blur();
				layout.setConfig();
				return false;
			});
			$('#tab_refresh').live('click', function(){
				layout.refreshAll();
				this.blur();
			}).addTipsy({gravity:'e'});
			$('#tab_minus').live('click', function(event){
				var a = Tab.$tabMenuNest.find('li.active');
				if(!a.prev().length){
					(new InfoNotification()).setMessage(_("You cannot remove the first tab.")).show()
					return false;
				} else if(!confirm('Really?')) {
					return false;
				}
				Tab.remove(a.attr('index'));
				layout.setConfig();
				//Tab.refresh();
				
				event.preventDefault();
				event.stopPropagation();
			});
			
			Tab.$tabMenuNest.find('li a').live('click', function(event){
				var $this = $(this).blur();
				var index = $this.parent().attr('index');
				Config.Layout.set('tabsActive', index);
				var i = Number(Tab.$tabMenuNest.find("li").index(Tab.$tabMenuNest.find("li.active")));
				if($('li.active',Tab.$tabMenuNest).attr('index') == index){
					layout.refreshAll();
					return false;
				}
				Tab.change(index);
				
				event.preventDefault();
				event.stopPropagation();
			}).live('mousedown', function(event) {
				dragndrop.seize(event, $(event.target).closest('li'), Tab.$tabMenuNest, 'li', 'grouptab_dummy', function() {
					var index = Tab.$tabMenuNest.find("li").index(dragndrop._target);
					var tabs = Config.Layout.get('tabs');
					var removed = tabs[dragndrop._index];
					tabs.splice(dragndrop._index, 1);
					tabs.splice(index, 0, removed);
					Config.Layout.set('tabs', tabs);
					Tab.refresh();
				});
			})
		}
		Tab.add = function(label){
			if(!Tab.config.tabsIndex)
				Tab.config.tabsIndex = 0;
			var i = ++Tab.config.tabsIndex;
			$('li', Tab.$tabMenuNest).removeClass('active');
			var n = Tab.template(label,i,true,Tab.$tabMenuNest.find('li').length+1);
			$('li:last',Tab.$tabMenuNest ).after(n);
			layout.destroy();
			layout.$grid_layout_tr = $('#grid_layout_tr');
			Tab.config.tabs.push({label:label,index:i, panels:[]});
		}
		Tab.change = function(index) {
			if(index==undefined)
				return false;
			var i = Tab.$tabMenuNest .find('li').removeClass('active').index(Tab.$tabMenuNest .find('li[index="'+index+'"]').addClass('active').addClass('loading'));
			//layout.deployPanelSet(i)
			setTimeout('layout.deployPanelSet('+i+');',200);
			setTimeout("Tab.$tabMenuNest .find('li').removeClass('loading')",1500);
		}
		Tab.rename = function(name, index) {
			Tab.config.tabs[index].label = name;
			$(Tab.$tabMenuNest.find("li a:first")[index]).text(name);
		}
		Tab.remove = function(index){
			if(index==undefined)
				return false;
			Tab.$tabMenuNest.find('li[index="'+index+'"]').remove();
			layout.deployPanelSet(0);
			$(Tab.$tabMenuNest.find('li')[0]).addClass('active');
			for( var i = 0 ; i < Tab.config.tabs.length; i++){
				if(Tab.config.tabs[i].index == index){
					Tab.config.tabs.splice(i,1);
				}
			}
		}
		Tab.refresh = function() {
			Tab.$tabMenuNest.find("li a:first").each(function(i, obj) {
				$(obj).attr('title', 'Group tab '+(i + 1)+'<div class=\'shortcut\'>Shortcut key : '+(i + 1)+'</div>').addTipsy({gravity:'s'});
			});
		}
		Tab.template = function(label,index,active,shortcut){
			return '<li'+(active ? ' class="active" ':' ')+'index="'+index+'"><a href="" title="Group tab '+shortcut+'<div class=\'shortcut\'>Shortcut key : '+shortcut+'</div>">'+label+'</a></li>';
		}
		Tab.init();
	}
	function Layout() {
		this.__construct();
	}
	
	Layout.panelSize = 330;
	
	$.extend(Layout.prototype, {
	    config: null,
		panels: new Array(),
		sidebar: 'show',
		$grid_layout_tr: null,
		
		_template: '\
			<ul class="control">\
				<li><a href="#" class="grid_refresh %{loading} %{mode}" title="refresh"><img src="" alt="" /></a></li><li><a href="#" class="grid_extends %{mode}" title="Click to %{title}"><img src="%{baseurl}images/%{mode}.png" alt="" /></a></li>\
			</ul>\
			<ul class="grid_list contextual %{mode}" style="display:none;">\
				%{close}\
				<li class="item" mode="@"><span>Mention @%{user}</span></li>\
				<li class="item" mode="DM"><span>' + _('Direct Messages') + '</span></li>\
				<li class="item" mode="favorites"><span>' + _('Favorites') + '</span></li>\
				<li class="item" mode="my"><span>' + _('Your tweets') + '</span></li>\
				<li class="item head"><span>' + _('Retweets...') + '</span>\
					<ul class="contextual" style="display:none;">\
						<li class="item" mode="retweets_by_others"><span>' + _('by others') + '</span></li>\
						<li class="item" mode="retweets"><span>' + _('by you') + '</span></li>\
						<li class="item" mode="retweeted_of_mine"><span>' + _('Your tweets, retweeted') + '</span></li>\
						<!-- li value="followers"><span>' + _('Followers') + '</span></li -->\
					</ul>\
				</li>',
			
		
		__construct: function() {
			if(!Setting.get('grid').value || $('body').attr('id') != 'home')
				return false;
			$('head').append('<style type="text/css">body.phoenix-skybar.monkeyfly{padding-top:0 !important}</style>');
			$('div.fixed-banners').animate({
			  top:-30
			},1000,function(){
				jQuery('body').mousemove(function(e){
					if(e.clientY<17){
						if(this.mode != 'show'){
							jQuery('div.fixed-banners').animate({top: 0})
						}
						this.mode = 'show';
					} else {
						if(this.mode != 'hide'){
							jQuery('div.fixed-banners').animate({top: -32})
						}
						this.mode = 'hide';
					}
				})	
			})
			this.$grid_layout_tr = $('#grid_layout_tr');
			this.registerEvents();
			$('#heading').after(this.createPanelPopupMenu('plus'));
			this.createHorizontalMenu();
			
			if (Config.Layout.get())
				this.config = Config.Layout.get();
			else
				this.config = {tabs:[{label:'Home', index:0, panels:[]}], tabsIndex:0, tabsActive:0, panelSize:Layout.panelSize, sidebar:this.sidebar};
			
			if (!this.config.tabsIndex)
				this.config.tabsIndex = 0;
			if (!this.config.tabsActive)
				this.config.tabsActive = 0;
			if (this.config.tabs == undefined || !this.config.tabs.length) {
				this.config.tabs = [{label:'Home', index:0, panels:[]}];
				this.config.tabsActive = 0;
			}
			if (this.config.panelSize == undefined)
				this.config.panelSize = Layout.panelSize;
			for (var i=0 ; i<this.config.tabs.length; i++) {
				if (!!this.config.tabs[i] && this.config.tabs[i].index == null) {
					this.config.tabs.splice(i,1);
					this.config.tabsActive = 0;
				}
			}
			
			$(page).watch("isTimelineChange", function(propertyName, oldValue, newValue) {
				if (!newValue) {
					$('.grid_refresh.plus').removeClass('loading');
					var s = $('#grid_layout_0 #heading').html();
					if (s != null) {
						var s = s.replace(/Tweets mentioning (@\w+)/, '$1');
						var s = s.replace(/Remove this saved search/, 'Remove');
						var s = s.replace(/Real-time results for <b>(.+?)<\/b>/, '$1');
						var s = s.replace(/Direct messages sent only to you/, 'Direct Messages');
						var s = s.replace(/Retweets by others/, 'by others');
						var s = s.replace(/Retweets by you/, 'by you');
						var s = s.replace(/Your tweets, retweeted/, 'your');
						$('#grid_layout_0 #heading').html(s);
						setTimeout('$(".save-search-link").isSaveSearchLink();$(".delete-search-link").isRemoveSearchLink();',1000);
					}
					if($('body').attr('id') == 'list'){
						$('h1#heading').after($('#grid_layout_0').find('a.grid_extends.plus, a.grid_refresh.plus'));
					}
				} else {
					$('.grid_refresh.plus').addClass('loading');
				}
			})

			var e = $('#retweet_tabs li a span');
			if (this.panels.length && e.length) {
				e.each(function() {
					$this = $(this);
					var s = $this.text();
					var s = s.replace(/Retweets by others/, 'by others');
					var s = s.replace(/Retweets by you/, 'by you');
					var s = s.replace(/Your tweets, retweeted/, 'your');
					$this.text(s);
				})
			}
			$ (window).resize(function() {
				this.repaint();
			}.pBind(this));
			if (Setting.get('gtab').value) {
				Tab(this.config);
			} else {
				this.deployPanelSet(0);
			}
			
			this.siebar_visible(this.config.sidebar == 'hide' ? 'hide' : 'show');
			
			$('#home_tab a').click(function() {
				$('#return-home').remove();
				$(document.body).attr('id', 'home');
				$('#timeline_heading').children('a').show();
			});
			
			$('#grid_layout td.panel div.grid_timeline_heading h1').live('mousedown', function(event) {
				dragndrop.seize(event, $(event.target).closest('div.grid_timeline_heading h1'), $('#grid_layout_tr'), 'td.panel', 'panel_dummy', function() {
					var tabIndex = Tab.$tabMenuNest.find("li").index(Tab.$tabMenuNest.find("li.active"));
					var index = $('#grid_layout_tr').find("td.panel").index(dragndrop._target);
					var tabs = Config.Layout.get('tabs');
					var removed = tabs[tabIndex].panels[dragndrop._index];
					tabs[tabIndex].panels.splice(dragndrop._index, 1);
					tabs[tabIndex].panels.splice(index, 0, removed);
					Config.Layout.set('tabs', tabs);
				});
			});
		},
		registerEvents: function() {
			$('.grid_list.plus li[mode]').live('click', function(event) {
				this.createPanel(event.target.parentNode);
			}.pBind(this));
			$('.grid_list.minus li[mode]').live('click', function(event) {
				this.changePanel(event.target.parentNode);
			}.pBind(this));
			
			$('.grid_extends img').live('click', function(event) {
				var target = $(event.target).parent();
				target.trigger('blur');
			
				var t = target.closest('td').find('.grid_list').css({right:'-3px', visibility:'hidden'}).show();
				var width = t.width();
				var column = target.closest('td.tdnest');
			
				if (column.length) {
					var match = target.closest('td.tdnest').attr('id').match(/grid_layout_([0-9]+)/);

					if (match[1] == $('#grid_layout_tr').find('td.tdnest').length - 1)
						t.addClass('last');
				}
			
				t.css({width:width+'px', visibility:'visible'});
			
				event.preventDefault();
				event.stopPropagation();
			});
			$('.grid_list').livequery('mouseleave', function() {
				$(this).hide();
			});
			$('.grid_refresh img').live('click', function(event) {
				var target = $(event.target).parent();
				
				if (target.hasClass('plus')) {
					this.refreshMainTimeline();
				} else if (this.panels.length) {
					var td = target.parents('td');
					var index = this.getIndexById((/grid_layout_(\d+)/.exec($(td[0]).attr('id')))[1]);
					this.panels[index-1].fetch();
				}
				
				event.preventDefault();
				event.stopPropagation();
			}.pBind(this));
			$('.grid_list.contextual>li.head').live('mouseover', function() {
				var target = $(this);
				var parent = target.closest('ul.contextual');
				var popup = target.find('ul.contextual').css({left: '-500px', visibility:'hidden'}).show();
				var width = popup.width();
				var left = parent.hasClass('last') ? -width + 5 : target.outerWidth() - 5;
				
				popup.css({top:'-5px', left:left+'px', width:width + 'px', visibility:'visible'});
			}).live('mouseout', function() {
				$(this).find('ul.contextual').hide();
			});
		},
		createPanelPopupMenu: function(mode) {
			var str = replaceParams(this._template, {
				baseurl: srcURL,
				mode: mode,
				title: (mode == 'minus' ? 'remove panel' : 'add panels'),
				user: user,
				loading: (mode == 'minus' ? 'loading' : ''),
				close: (mode == 'minus' ? '<li class="item" mode="close"><span>' + _('Close') + '</span></li>' : '')
			});
			
			var items = $('.sidebar-menu.lists-links li a');

			if (items.length) {
				str += '<li class="item head"><span>' + _('Lists...') + '</span><ul class="contextual" style="display:none;">';

				items.each(function(){
					var data = JSON.parse($(this).attr('data'));
					str += '<li class="item" mode="lists" user="'+data.user+'" mode="'+data.mode+'" slug="'+data.slug+'"><span>'+data.full_name+'</span></li>';
				});

				str+='</ul></li>';
			}
			
			var items = $('.sidebar-menu.saved-search-links li a span');

			if (items.length) {
				var sstr = '';
				str += '<li class="item head"><span>' + _('Saved keywords...') + '</span><ul class="contextual" style="display:none;">';

				items.each(function(){
					var title = $(this).text();
					sstr += '<li class="item" mode="searches" keyword="'+title+'"><span>'+title+'</span></li>';
				});
				
				if (sstr.length)
					str += '<li class="item" mode="searches" keyword="_all" class="first"><span>' + _('All') + '</span></li>'+sstr;
				
				str+='</ul></li>';
			}

			str += '</ul>';

			return str;
		},
		createHorizontalMenu: function() {
			this._content = $('#content');
			this._content.append('<a id="expand_sidebar" class="hide" href="#"><img src="" class="show" /><img src="" class="hide" /></a>');
			this._sidebase = $('#side_base');
			
			this._sidebartoggler = $('#expand_sidebar');
			$('img', this._sidebartoggler).click(function(event){
				this.siebar_visible($(event.target).hasClass('hide') ? 'hide' : 'show');
				this.setConfig();
				event.preventDefault();
				event.stopPropagation();
			}.pBind(this));
			
			$(document.body).append('\
				<ul id="banana" style="display:none;">\
					<li class="bclose"><a href="#">menu</a></li>\
					<li class="bmenu"><a href="#menu">Menu</a></li>\
					<li class="bsearches"><a href="#searches">Searches</a></li>\
					<li class="blist"><a href="/'+user+'/lists/memberships"><span class="label">Lists</span><span class="count">'+$('#lists_count').text()+'</span></a></li>\
					<li class="bfollowing"><a href="/following"><span class="label">Following</span><span class="count">'+$('#following_count').text()+'</span></a></li>\
					<li class="bfollowers"><a href="/followers"><span class="label">Followers</span><span class="count">'+$('#follower_count').text()+'</span></a></li>\
					<li class="btweets"><a href="/'+user+'"><span class="label">Tweets</span><span class="count">'+$('#update_count').text()+'</span></a></li>\
				</div>');
			$('#status_update_box').after('<div id="width_helper"></div>');
			
			this._banana = $('#banana').hide();
			
			$('li.bclose a', this._banana).click(function(event) {
				if (this._banana.hasClass('small')) {
					this._banana.removeClass('small').css({top:($(window).height()-this._banana.height()-4)+'px', left:($(window).width()/2-this._banana.width()/2)+'px'});
				} else {
					$('ul.contextual', this._banana).hide();
					this._banana.addClass('small').css({top:($(window).height()-this._banana.height())+20+'px', left:($(window).width()/2-this._banana.width()/2)+'px'});
				}
				
				event.preventDefault();
				event.stopPropagation();
			}.pBind(this));
			
			$('li.bmenu', this._banana).append('\
				<ul id="banana_menu" class="contextual" style="display:none;">\
					<li id="bhome_tab" class="item"><a><span>Home</span></a></li>\
					<li id="breplies_tab" class="item"><a><span>@'+user+'</span></a></li>\
					<li id="bdirect_messages_tab" class="item"><a><span>Direct Messages</span></a></li>\
					<li id="bfavorites_tab" class="item"><a><span>Favorites</span></a></li>\
					<li id="blinks_tab" class="item"><a><span>Links</span></a></li>\
				</ul>');
			this._menu_contextual = $('#banana_menu');
			$('li', this._menu_contextual).click(function() {
				var id = $(this).attr('id');
				switch(id){
				case 'bhome_tab':
				case 'breplies_tab':
				case 'bdirect_messages_tab':
				case 'bfavorites_tab':
				case 'blinks_tab':
					$('#side #'+id.substr(1	)+' a:first').trigger('click');
					break;
				}
			});
			
			var keywords = $('.sidebar-menu.saved-search-links li');
			if (keywords.length) {
				$('li.bsearches', this._banana).append('<ul id="banana_searches" class="contextual" style="display:none;"></ul>');
				keywords.each(function(i, obj) {
					$('#banana_searches').append($(obj).clone().addClass('item'));
				});
				$('li a', '#banana_searches').isSearchLink(SEARCH_CALLBACKS.savedSearchLink);
			}
			this._search_contextual = $('#banana_searches');
			
			var lists = $('.sidebar-menu.lists-links li');
			if (lists.length) {
				$('li.blist', this._banana).append('<ul id="banana_lists" class="contextual" style="display:none;"></ul>');
				lists.each(function(i, obj) {
					$('#banana_lists').append($(obj).clone().addClass('item').click(function() {
						$('#side .sidebar-menu.lists-links '+$(this).find('a').attr('class').replace(/(.+) (.+)/,'.$1.$2')).trigger('click');
						return false;
					}));
				});
			}
			this._list_contextual = $('#banana_lists');
			
			this._banana.children().mouseover(function() {
				$(this).find('ul.contextual').show();
			}).mouseleave(function() {
				$(this).find('ul.contextual').hide();
			});
		},
		createPanel: function(target) {
			target = $(target);
			
			switch (target.attr('mode')) {
			case '@':
			case 'my':
			case 'favorites':
			case 'DM':
			case 'followers':
			case 'retweets_by_others':
			case 'retweets':
			case 'retweeted_of_mine':
				p = this.getPanelInstance(target.attr('mode'));
				break;
			case 'lists':
				p = new PanelLists(target.attr('user'), target.attr('slug'));
				break;
			case 'searches':
				p = new PanelSearches(target.attr('keyword'));
				break;
			}
			
			this.add(p);
			target.parent().hide();
		},
		changePanel: function(target) {
			target = $(target);
			var index = (/grid_layout_(\d+)/.exec($(target.parents('td')[0]).attr('id')))[1];
			
			switch(target.attr('mode')){
			case 'DM':
				this.change(index, (new PanelDM()));
				break;
			case 'favorites':
				this.change(index, (new PanelFavorites()));
				break;
			case 'my':
				this.change(index, (new PanelMy()));
				break;
			case '@':
				this.change(index, (new PanelMention()));
				break;
			case 'close':
				this.remove(index);
				break;
			case 'lists':
				this.change(index, (new PanelLists(target.attr('user'), target.attr('slug'))));
				break;
			case 'retweets_by_others':
			case 'retweets':
			case 'retweeted_of_mine':
				this.change(index, (new PanelRetweets(target.attr('mode'))));
				break;
			case 'searches':
				this.change(index, (new PanelSearches(target.attr('keyword'))));
				break;
			}
			
			this.setConfig();
			target.parent().hide();
		},
		refreshMainTimeline: function() {
			var action = $('body').attr('id');
			switch(action){
			case 'home':
			case 'replies':
			case 'inbox':
			case 'sent':
			case 'favorites':
			case 'retweets_by_others':
			case 'retweets':
			case 'retweeted_of_mine':
				$("#"+action+"_tab .in-page-link").trigger('click');
				break;
			case 'search':
				var d = $('.delete-search-link');
				var s = $('.save-search-link');
				if (d.length > 0) {
					$('.search-link[title="'+$('.delete-search-link').attr('title')+'"]').trigger('click');
				} else {
					$('.search_link[title="'+$('.save-search-link').attr('title')+'"]').trigger('click');
				}
				break;
			case 'list':
				$('#side_lists li a[href="'+$('p.list-link a').attr('href')+'"]').trigger('click');
				break;
			}
		},
		refreshAll: function() {
			for (var i=0; i<this.panels.length ; i++)
				this.panels[i].fetch();
			
			$('#tab_refresh').addClass('loading');
			$.ajax({
				url : '/users/show.json?screen_name='+user,
				type:'GET',
				dataType:'json',
				success:function(e){
					$('#following_count.stats_count.numeric').text(numberWithDelimiter(e.friends_count));
					$('#follower_count.stats_count.numeric').text(numberWithDelimiter(e.followers_count));
					$('#update_count').text(numberWithDelimiter(e.statuses_count));
					$('.bfollowing span.count').text(numberWithDelimiter(e.friends_count));
					$('.bfollowers span.count').text(numberWithDelimiter(e.followers_count));
					$('.btweets span.count').text(numberWithDelimiter(e.statuses_count));
					$('#tab_refresh').removeClass('loading');
				}
			})
			this.refreshMainTimeline();
		},
		deployPanelSet: function(index) {
			var panels = this.config.tabs[index].panels;
			this.panels = [];
			this.$grid_layout_tr.find('td.tdnest:gt('+panels.length+')').remove();
			if (panels.length) {
				this.init_repaint();
				for (var i=0 ; i<panels.length; i++) {
					var panel = panels[i];
					if (!panel)
						continue;
					var target = this.$grid_layout_tr.find('td.tdnest').get(i+1);
					this._add(this.getPanelInstance(panel), target ? target : null);
				}
			}

			if (this.$grid_layout_tr.find('td.tdnest').length < 2)
				this.destroy();
			this.repaint();
		},
		getPanelInstance: function(panel) {
			var p = null;
			
			switch (panel) {
			case '@':
			case 'mention':
				p = new PanelMention();
				break;
			case 'my':
				p = new PanelMy();
				break;
			case 'favorites':
				p = new PanelFavorites();
				break;
			case 'DM':
				p = new PanelDM();
				break;
			case 'follow':
			case 'followers':
				p = new PanelFollow('followers');
				break;
			case 'retweets_by_others':
			case 'retweets':
			case 'retweeted_of_mine':
				p = new PanelRetweets(panel);
				break;
			default:
				if (panel.indexOf('lists') == 0) {
					var r = panel.match(/lists\/@(.+)\/(.+)/);
					p = new PanelLists(r[1], r[2]);
				} else if (panel.indexOf('searches') == 0) {
					var r = panel.match(/searches\/#(.+)/);
					p = new PanelSearches(r[1]);
				}
			}
			
			return p;
		},
		getIndexById: function(id) {
			for (var i=0 ; i<$('#grid_layout td[id]').length; i++) {
	    		if ($('#grid_layout td[id]')[i].id == 'grid_layout_'+id)
					return  i;
			}
		},
	   	remove: function(id) {
			var index = this.getIndexById(id);
			this.panels.splice(index-1,1);
			$('#grid_layout_'+id+'[id]').remove();
			if ($('#grid_layout td').length == 1)
				this.destroy();
			else
				this.repaint();
		},
		change: function(id, panel) {
			var index = this.getIndexById(id);
			this.panels.splice(index-1,1, panel);
			var p = $('#grid_layout_'+id+'[id]').prev();

			$('#grid_layout_'+id).remove();
			p.after("<td mode=\""+panel.mode+"\" id=\"grid_layout_"+id+"\" class=\"tdnest\"></td>");
			panel.init($('#grid_layout_'+id));
			$('#grid_layout_'+id+' .grid_timeline_heading h1').after(this.createPanelPopupMenu('minus'));
			this.repaint();
		},
		setConfig: function() {
			var panels = [];
			var p = $('#grid_layout td[mode]');
			for (var i=0, _i=p.length; i<_i ; i++) {
				panels.push($(p[i]).attr('mode'))
			}
			if (Setting.get('gtab').value) {
				var index = Tab.$tabMenuNest.find('.active').attr('index');
				for (var i=0; i<this.config.tabs.length; i++) {
					var t = this.config.tabs[i];
					if (t.index == index) {
						this.config.tabs[i].panels = panels;
						break;
					}
				}
				this.config.tabsActive = index;
			} else {
				this.config.tabs[0].panels = panels;
			}
			if(this._sidebase.is(':visible'))
				this.config.sidebar='show';	
			else
				this.config.sidebar='hide';	
			
			Config.Layout.set('', this.config);
		},
		siebar_visible: function(visible) {
			if(visible == 'hide'){
				this._sidebartoggler.addClass('show').removeClass('hide');
				this._sidebase.hide();
				this.config.sidebar = 'hide';
				this._banana.show().addClass('small');
				
				if (!window.is_PBTweet)
					this._content.css({'border-top-right-radius': '5px 5px', 'border-bottom-right-radius': '5px 5px'})
			} else {
				this._sidebartoggler.addClass('hide').removeClass('show');
				this._sidebase.show();
				this.config.sidebar = 'show';
				this._banana.hide();
				
				if (!window.is_PBTweet)
					this._content.css({'border-top-right-radius': 0, 'border-bottom-right-radius': 0})
			}
			this._sidebartoggler.blur();
			this.repaint();
		},
		add: function(panel) {
			this._add(panel);
			this.setConfig();
			this.repaint();
		},
		_add: function(panel, target) {
			if ($('#grid_layout').length == 0 ) {
				var lastSection = $('#content div.wrapper div.section');
				$(lastSection[lastSection.length-1]).wrap('<table id="grid_layout"><tr id="grid_layout_tr"><td id="grid_layout_0" class="tdnest"></td></tr></table>');
				this.$grid_layout_tr = $('#grid_layout_tr');
				$('body').addClass('grid');
			}
			if (target) { // 패널이 이미 존재한다면 재활용하기 위한 로직
				var $target = $(target);
				if ($target.attr('mode') == panel.mode) {
					$target.data('instance').fetch();
					panel = $target.data('instance');
					//nest.fetch();
				} else {
					var nest = $target.attr('mode',panel.mode).html('');
					panel.init(nest);
					nest.find('.grid_timeline_heading h1').after(this.createPanelPopupMenu('minus'));
				}
			} else {
				var nest = $('<td mode="'+panel.mode+'" id="grid_layout_'+($('#grid_layout td').length)+'" class="tdnest panel"></td>');
				this.$grid_layout_tr.append(nest);
				panel.init(nest);
				nest.find('.grid_timeline_heading h1').after(this.createPanelPopupMenu('minus'));
			}
			this.panels.push(panel);
			this.repaint();
		},
		init_repaint: function() {
			var stageWidth = $(document.body).width();
			var contentWidth = stageWidth - (!this._sidebase.is(':visible') ? 0 : this._sidebase.width()) - 20;
			var eachWidth = Math.min(500, Math.max(250, Math.ceil(contentWidth/this.$grid_layout_tr.find('td.tdnest').length-28)));
			var p = Layout.panelSize;
			Layout.panelSize = eachWidth;
			var flag = false;
			this.$grid_layout_tr.find('.section').each(function(i, obj) {
				if ($(obj).width() != Layout.panelSize) {
					flag = true;
					return false;
				}
			}.pBind(this));
			if (p != Layout.panelSize || flag) {
				$('head').find('#panelCss').remove()
				$('head').append('<style type="text/css" id="panelCss" class="monkeyflyPanelCss">body.grid #grid_layout div.section{width:'+Layout.panelSize+'px !important;}</style>');
			}
		},
		repaint: function() {
			this.init_repaint();
			var gl = $('#grid_layout td').length > 1 ? $('#grid_layout').width() : 542;
			var ib = $('.common-form.standard-form');
			if (!this._sidebase.is(':visible')) {
				var side_w = 0;
				this._content.css('-moz-border-radius-topright','5px');
				//$('#side_base').css('visibility','hidden');
			} else {
				var side_w = this._sidebase.width();
				this._content.css('-moz-border-radius-topright','0');
				//$('#side_base').css('visibility','visible');
			}
			$('#container').css('width', (gl+20+side_w+1)+'px');
			this._sidebartoggler.css({top:'272px', marginLeft:(this._content.width()-8)+'px'});
			this._banana.css({top:($(window).height()-this._banana.height())+(this._banana.hasClass('small') ? 20 : -4)+'px', left:($(window).width()/2 - this._banana.width()/2)+'px'});
			var banana_left = parseInt(this._banana.css('left')) - 2;
			this._list_contextual.css({bottom:this._banana.height()-13+'px'});
			this._search_contextual.css({bottom:this._banana.height()-13+'px'});
			this._menu_contextual.css({bottom:this._banana.height()-13+'px'});
		},
		destroy: function() {
			$('.wrapper').append($('#grid_layout td:first .section'));
			$('#grid_layout').remove();
			$('body').removeClass('grid');
			$('#container').css('width','');
			$('.common-form.standard-form').css({width:'', margin:'', padding:''});
			this.$grid_layout_tr = $('#grid_layout_tr');
			this.panels = new Array();
			this.repaint();
		}
	})

	function Panel(nest) {};

	jQuery.extend(Panel.prototype, {
		nextpage: null,
		max_id: null,
		nest: null,
		header: '\
			<div class="section  grid %{mode} grid">\
				<div class="grid_timeline_heading %{id}">\
					<h1 id="heading_%{id}">%{link}</h1>\
				</div>\
				<ol id="timeline" class="statuses %{id}"></ol>\
				<div id="grid_pagination" class="%{id}"></div>\
			</div>',

		init: function(nest) {
			this.nest = nest;
			this.nest.append(this.createHeader());
			$(this.nest).data('instance', this);

			this.fetch();

			$('#grid_pagination.'+this.id).live('click', function() {
				this.fetch(this.nextpage, this.max_id);
				return false;
			}.pBind(this));
		},
		fetch: function(nextpage, max_id) {
			// interface
		},
		createHeader: function() {
			// interface
		},
		processForTweet: function(str) {
			return str.replace(/(<ol.+>)|(<\/ol>)/g,'');
		},
		processForPagination: function(json) {
			var p = json['#pagination'].match(/max_id=(\d+)&amp;page=(\d{1,})/);
			this.max_id = p[1];
			this.nextpage = p[2];
			$('#grid_pagination.'+this.id).html('<a rel="next" id="more" href="#" class="round more">' + _('more') + '</a>');
		},
		_fetch: function(nextpage, max_id, url){
			$('#grid_pagination.'+this.id+' a.round.more').addClass('loading').html('');

			$.getJSON(url, {}, function (json) {
				this.nest.find('.grid_refresh').removeClass('loading')[0].blur();

				if (nextpage == undefined)
					$('#timeline.'+this.id+'.statuses').html(this.processForTweet(json['#timeline']));
				else
					$('#timeline.'+this.id+'.statuses').append(this.processForTweet(json['#timeline']));
				
				Reply.refresh($('#timeline.'+this.id+'.statuses'));
				$.Statuses.initialize($('#timeline.'+this.id));

				if(json['#pagination'] == null) {
					$('#grid_pagination.'+this.id).hide();
					return;
				}

				this.processForPagination(json);
			}.pBind(this));

			this.nest.find('.grid_refresh').addClass('loading');
		}
	})

	PanelMention = function() {};
	PanelMention.prototype = new Panel();

	jQuery.extend(PanelMention.prototype, {
		mode: 'mention',
		id: 'mention_'+(Math.floor(10000*Math.random())),

		createHeader: function() {
			$('head').append('<style type="text/css">.section.'+this.mode+'{width:'+Layout.panelSize+'px !important;}</style>');

			return replaceParams(this.header, {mode:this.mode, id:this.id, link:'<a href="/#replies">@'+user+'</a>'});
		},
		fetch: function(nextpage, max_id){
			$('#grid_pagination.'+this.id+' a.round.more').addClass('loading').html('');

			$.getJSON(nextpage==null || max_id==null ? '/replies' : '/replies?max_id='+max_id+'&page='+nextpage+'&twttr=true', {}, function (json) {
				this.nest.find('.grid_refresh').removeClass('loading')[0].blur();

				if (nextpage == undefined)
					$('#timeline.'+this.id+'.statuses').html(this.processForTweet(json['#timeline']));
				else
					$('#timeline.'+this.id+'.statuses').append(this.processForTweet(json['#timeline']));

				try {
					this.processForPagination(json);
				} catch(e) {}
			
				Reply.refresh($('#timeline.'+this.id+'.statuses'));
				$.Statuses.initialize($('#timeline.'+this.id));
			}.pBind(this));

			this.nest.find('.grid_refresh').addClass('loading');
		}
	});

	PanelMy = function() {};
	PanelMy.prototype = new Panel();

	jQuery.extend(PanelMy.prototype, {
		mode: 'my',
		id: 'my_'+(Math.floor(10000*Math.random())),

		createHeader: function() {
			$('head').append('<style type="text/css">.section.'+this.mode+'{width:'+Layout.panelSize+'px !important;} .section.'+this.mode+' .mine .thumb.vcard.author{display:none;} .section.'+this.mode+' .actions{width:16px; right:0}</style>');
			return replaceParams(this.header, {mode:this.mode, id:this.id, link:'<a href="/'+user+'">' + _('Your tweets') + '</a>'});
		},
		fetch: function(nextpage, max_id) {
			this._fetch(nextpage, max_id, (nextpage==null || max_id==null) ? '/'+user+'?page=1&twttr=true' : '/'+user+'?max_id='+max_id+'&page='+nextpage+'&twttr=true');
		}
	});

	PanelFavorites = function() {};
	PanelFavorites.prototype = new Panel();

	jQuery.extend(PanelFavorites.prototype, {
		mode: 'favorites',
		id: 'favorites_'+(Math.floor(10000*Math.random())),

		createHeader: function() {
			$('head').append('<style type="text/css">.section.'+this.mode+'{width:'+Layout.panelSize+'px !important;}</style>');
			return replaceParams(this.header, {mode:this.mode, id:this.id, link:'<a href="/#favorites">' + _('Favorites') + '</a>'});
		},
		fetch: function(nextpage, max_id){
			this._fetch(nextpage, max_id, (nextpage==null || max_id==null) ? '/favorites' : '/favorites?max_id='+max_id+'&page='+nextpage+'&twttr=true');
		}
	});

	PanelDM = function() {};
	PanelDM.prototype = new Panel();

	jQuery.extend(PanelDM.prototype, {
		mode: 'DM',
		id: 'DM_'+(Math.floor(10000*Math.random())),
		method: 'inbox',
		header: '\
			<div class=\"section grid %{mode}">\
				<div class=\"grid_timeline_heading %{id}">\
					<h1 id=\"heading_%{id}"><a href="/#inbox">' + _('Direct Messages') + '</a></h1>\
					<ul class="tabMenu" style="display:block">\
					  <li id="inbox_tab_%{id}" class="dm_%{id} active"><a href="/inbox"><span>' + _('inbox') + '</span></a></li>\
					  <li id="sent_tab_%{id}" class="dm_%{id}"><a href="/sent"><span>' + _('sent') + '</span></a></li>\
					</ul>\
				</div>\
				<ol id=\"timeline\" class=\"statuses %{id}"></ol>\
				<div id="grid_pagination" class="%{id}"></div>\
			</div>',

		init: function(nest){
			this.nest = nest;

			$('.'+this.id+' .replydm a').live('click', function(){
				if($('body').attr('id') == 'inbox' || $('body').attr('id') == 'sent'){
					var t = $(this).attr('title').match(/reply to (\w+)/)[1];
					$('#direct_message_user_id option').each(function(){
						if($(this).text() == t){
							$(this).attr('selected', 'selected');
							$('#text')[0].focus();
							return false;
						}
					});
				} else {
					$('#status')[0].value = $(this).attr('title').replace(/reply to (\w+)/, 'd @$1 ');
					$('#status')[0].focus();
				}

				return false;
			});

			this.nest.append(this.createHeader());
			$(nest).data('instance',this);

			this.fetch();

			$('#grid_pagination.'+this.id).live('click', function(){
				this.fetch(this.nextpage, this.max_id);

				return false;
			}.pBind(this));

			$('.dm_'+this.id).live('click', function(event){
				var method = ($(event.target).text().match(/(sent|inbox)/i))[1];
				this.fetch(null, null, method.toLowerCase());

				return false;
			}.pBind(this));
		},
		createHeader: function() {
			$('head').append('<style type="text/css">.section.'+this.mode+'{width:'+Layout.panelSize+'px !important;} #content .section.'+this.mode+' .tabMenu li.active a {background-color:#FFFFFF;border-color:#C4C4C4 #C4C4C4 #FFFFFF;border-style:solid;border-width:1px;color:#333333;margin-right:1px;padding:5px 14px;}#content .section.'+this.mode+' .tabMenu li.loading a {background-image:url('+srcURL+'images/spinner.gif);background-position:center center;background-repeat:no-repeat;color:transparent !important}#timeline.statuses.'+this.id+'{border-top:solid 1px #ccc!important;}#timeline.statuses.'+this.id+' li:first-child{border-top:none;}</style>');
			return replaceParams(this.header, {mode:this.mode, id:this.id});
		},
		fetch: function(nextpage, max_id, method){
			this.method = (method == undefined ? this.method : method);

			$('#grid_pagination.'+this.id+' a.round.more').addClass('loading').html('');
			$('.dm_'+this.id).removeClass('active');
			$('#'+this.method+'_tab_'+this.id).addClass('active loading');

			$.getJSON(nextpage==null || max_id==null ? '/'+this.method : '/'+this.method+'?max_id='+max_id+'&page='+nextpage+'&twttr=true', {}, function (json) {
				this.nest.find('.grid_refresh').removeClass('loading')[0].blur();
				json['#timeline'] = json['#timeline'].replace(/<span class="reply">/g, '<span class="replydm">');

				if (nextpage == undefined)
					$('#timeline.'+this.id+'.statuses').html(this.processForTweet(json['#timeline']));
				else
					$('#timeline.'+this.id+'.statuses').append(this.processForTweet(json['#timeline']));
			
				Reply.refresh($('#timeline.'+this.id+'.statuses'));
				$.Statuses.initialize($('#timeline.'+this.id));
				$('.dm_'+this.id).removeClass('loading');

				if(json['#pagination'] == null) {
					$('#grid_pagination.'+this.id).hide();
					return;
				}

				this.processForPagination(json);
			}.pBind(this));

			this.nest.find('.grid_refresh').addClass('loading');
		}
	});

	PanelRetweets = function(method) {
		this.__construct(method)
	};
	PanelRetweets.prototype = new Panel();

	jQuery.extend(PanelRetweets.prototype, {
		mode: null,
		id: null,
		method: null,
		header: '\
			<div class=\"section grid %{mode}">\
				<div class=\"grid_timeline_heading %{id}">\
					<h1 id=\"heading_%{id}"><a href="/#inbox">%{label}</a></h1>\
					<ul class="tabMenu" id="retweet_tabs" style="display:block">\
					  <li id="retweets_by_others_tab_%{id}" class="retweets_by_others"><a mode="retweets_by_others" data="{dispatch_action:\'retweets_by_others\'}" href="/retweets_by_others"><span>' + _('by others') + '</span></a></li>\
					  <li id="retweets_tab_%{id}" class="retweets"><a mode="retweets" data="{dispatch_action:\'retweets\'}" href="/retweets"><span>' + _('by you') + '</span></a></li>\
					  <li id="retweeted_of_mine_tab_%{id}" class="retweeted_of_mine"><a mode="retweeted_of_mine" data="{dispatch_action:\'retweeted_of_mine\'}" href="/retweeted_of_mine"><span>' + _('yours') + '</span></a></li>\
					</ul>\
				</div>\
				<ol id=\"timeline\" class=\"statuses %{id}"></ol>\
				<div id="grid_pagination" class="%{id}"></div>\
			</div>',

		__construct: function(method) {
			this.mode = method;
			this.id = method+'_'+(Math.floor(10000*Math.random()));
			this.method = method;
		},
		init: function(nest){
			this.nest = nest;

			this.nest.append(this.createHeader());
			$(this.nest).data('instance',this);

			this.fetch();

			$('#grid_pagination.'+this.id).live('click', function() {
				this.fetch(this.nextpage, this.max_id);

				return false;
			}.pBind(this));

			$('.'+this.id+' .tabMenu li a').live('click', function(event) {
				try {
					var method = $(event.target).parent().attr('mode');
				} catch(e) {
					var method = 'retweeted_of_mine_tab_';
				}
				this.fetch(null, null, method);

				return false;
			}.pBind(this));
		},
		createHeader: function() {
			$('head').append('<style type="text/css">.section.'+this.mode+'{width:'+Layout.panelSize+'px !important;} #content .section.'+this.mode+' .tabMenu li.active a {background-color:#FFFFFF;border-color:#C4C4C4 #C4C4C4 #FFFFFF;border-style:solid;border-width:1px;color:#333333;margin-right:1px;padding:5px 14px;}#content .section.'+this.mode+' .tabMenu li.loading a {background-image:url('+srcURL+'images/spinner.gif);background-position:center center;background-repeat:no-repeat;color:transparent !important}#timeline.statuses.'+this.id+'{border-top:solid 1px #ccc!important;}#timeline.statuses.'+this.id+' li:first-child{border-top:none;}</style>');

			var label = _('Retweets');
			
			return replaceParams(this.header, {label:label, mode:this.mode, id:this.id});
		},
		fetch: function(nextpage, max_id, method){
			this.method = (method == undefined ? this.method : method);
			$('#grid_pagination.'+this.id+' a.round.more').addClass('loading').html('');
			$('#'+this.method+'_tab_'+this.id).addClass('active').addClass('loading');
			$.getJSON(nextpage==null || max_id==null ? '/'+this.method : '/'+this.method+'?max_id='+max_id+'&page='+nextpage+'&twttr=true', {}, function (json) {
				this.nest.find('.grid_refresh').removeClass('loading')[0].blur();
				json['#timeline'] = json['#timeline'].replace(/<span class="reply">/g, '<span class="replydm">');

				if (nextpage == undefined)
					$('#timeline.'+this.id+'.statuses').html(this.processForTweet(json['#timeline']));
				else
					$('#timeline.'+this.id+'.statuses').append(this.processForTweet(json['#timeline']));
				
				Reply.refresh($('#timeline.'+this.id+'.statuses'));
			
				$('.'+this.id+' .tabMenu li').removeClass('loading').removeClass('active');
				$('.'+this.id+' .tabMenu li.'+this.method).addClass('active');

				$.Statuses.initialize($('#timeline.'+this.id));
				$('.dm_'+this.id).removeClass('loading');

				if(json['#pagination'] == null) {
					$('#grid_pagination.'+this.id).hide();
					return;
				}

				this.processForPagination(json);
			}.pBind(this));

			this.nest.find('.grid_refresh').addClass('loading');
		}
	});

	PanelLists = function(user, slug) {
		this.__construct(user, slug);
	};
	PanelLists.prototype = new Panel();

	jQuery.extend(PanelLists.prototype, {
		mode: null,
		id: null,
		user: null,
		slug: null,

		__construct: function(user, slug) {
			this.mode = 'lists/@'+user+'/'+slug;
			this.id = 'lists_'+(Math.floor(10000*Math.random()));
			this.user = user;
			this.slug = slug;
		},
		createHeader: function() {
			$('head').append('<style type="text/css">.section.'+this.mode+'{width:'+Layout.panelSize+'px !important;}</style>');
			return replaceParams(this.header, {mode:this.mode, id:this.id, link:'<a href="/'+this.user+'/'+this.slug+'">@'+this.user+'/'+this.slug+'</a>'});
		},
		fetch: function(nextpage, max_id){
			this._fetch(nextpage, max_id, (nextpage==null || max_id==null) ? '/'+this.user+'/'+this.slug : '/'+this.user+'/lists/'+this.slug+'?max_id='+max_id+'&page='+nextpage+'&twttr=true');
		}
	});

	PanelSearches = function(slug) {
		this.__construct(slug);
	};
	PanelSearches.prototype = new Panel();

	jQuery.extend(PanelSearches.prototype, {
		mode: null,
		id: null,
		keyword: null,
		keywords: [],
		body: '\
			<li id="status_%{id}" class="hentry status search_result u-%{from_user}">\
				<span class="thumb vcard author">\
					<a href="/%{from_user}" class="tweet-url profile-pic"><img class="photo fn" src="%{profile_image_url}" alt="" /></a>\
				</span>\
				<span class="status-body">\
					<span class="status-content">\
						<strong><a href="/%{from_user}" class="tweet-url screen-name">%{from_user}</a></strong>\
						<span class="actions">\
							<div><a id="status_star_%{id}" class="fav-action non-fav" href="#" title="favorite this tweet"></a></div>\
						</span>\
						<span class="entry-content msgtxt en" id="msgtxt%{id}">%{text}</span>\
					</span>\
					<span class="meta entry-meta"><a href="/%{from_user}/statuses/%{id}">%{time}</a></span>\
					<ul class="actions-hover">\
						%{actions}\
					</ul>\
				</span>\
			</li>',
		actions: {
			other: '<li>\
					<span class="reply">\
						<span class="reply-icon icon"></span>\
						<a href="/?status=@%{from_user}%20&amp;in_reply_to_status_id=%{id}&amp;in_reply_to=%{from_user}">Reply</a>\
					</span>\
				</li>\
				<li>\
					<span class="retweet-link">\
						<span class="retweet-icon icon"></span>\
						<a title="Retweet" href="#">Retweet</a>\
					</span>\
				</li>',
			you: '<li><span class="del"><span class="delete-icon icon"/><a title="delete this tweet" href="#">Delete</a></span></li>'
			
		},
		
		__construct: function(keyword) {
			this.mode = 'searches/#'+keyword;
			this.id = 'searches_'+(Math.floor(10000*Math.random()));
			this.keywords = [];
			this.keyword = keyword;

			if(keyword == '_all'){
				$('.sidebar-menu.saved-search-links li a span').each(function(i, obj){
					this.keywords.push($(obj).text());
				}.pBind(this))
			} else {
				this.keywords.push(keyword);
			}
		},
		createHeader: function() {
			$('head').append('<style type="text/css">.section.'+this.mode+'{width:'+Layout.panelSize+'px !important;}</style>');
			if (this.keywords.length > 1) {
				var _keyword = [];
				for(var i = 0; i < this.keywords.length ; i++){
						var k = this.keywords[i];
						_keyword.push(k.charAt(0) == '#' ? k : '#'+k);
				}
				var keyword = _keyword.join(',');
			} else {
				var keyword = this.keyword.charAt(0) == '#' ? this.keyword : '#'+this.keyword;
			}
			return replaceParams(this.header, {mode:this.mode, id:this.id, link:'<a href="/#search?q='+this.keyword+'">'+keyword+'</a>'})
		},
		fetch: function(nextpage, max_id){
			$('#grid_pagination.'+this.id+' a.round.more').addClass('loading').html('');

			var k = '';
			var escaped = [];
			for (var i=0 ; i<this.keywords.length; i++)
				escaped.push(encodeURIComponent(this.keywords[i]));
			try{
				$.get(nextpage==null ? 'http://search.twitter.com/search.json?q='+(escaped.join('+OR+'))+'&rpp=20&maxId=null' : 'http://search.twitter.com/search.json'+nextpage, {}, function (json) {
					try {
						this.nest.find('.grid_refresh').removeClass('loading')[0].blur();
						var strs = '';
						var str = '';
						var result = null;
						var d = null;
						var m = ['Jan','Feb','Mar','Apr','May','June', 'Jul', 'Aug','Sep', 'Oct','Nov', 'Dec'];
						var t = null;
						
						for (var i=0; i<json.results.length; i++) {
							
								result = json.results[i];
								
								d = new Date(Date.parse(result.created_at));
								t = (d.getHours()%12)+':'+d.getMinutes()+' '+(d.getHours()>12 ? 'PM' : 'AM')+' '+m[d.getMonth()]+' '+d.getDate()+'th';
		
								result['text'] = result['text'].replace(/@(\w+)/g,'<a href="/$1" class="tweet-url username">@$1</a>');
								result['text'] = result['text'].replace(/#(\w+)/g,'<a class="tweet-url hashtag" title="#$1" href="/search?q=%23$1">#$1</a>');
								result['text'] = result['text'].replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,"<a href=\"$1\" target=\"_blank\">$1</a>");
								result['text'] = result['text'].replace('<a href="http://', '<a class="tweet-url web" href="http://', 'gi');
		
								strs += replaceParams(this.body, {
									actions: result['from_user'] == user ? this.actions.you : this.actions.other,
									id: result['id'],
									from_user: result['from_user'],
									profile_image_url: result['profile_image_url'],
									text: result['text'],
									time: t
								});
							
						}
		
						if (nextpage == undefined)
							$('#timeline.'+this.id+'.statuses').html(this.processForTweet(strs));
						else
							$('#timeline.'+this.id+'.statuses').append(this.processForTweet(strs));
					
						Reply.refresh($('#timeline.'+this.id+'.statuses'));
						$.Statuses.initialize($('#timeline.'+this.id));
		
						this.nextpage = json.next_page;
						$('#grid_pagination.'+this.id).show().html('<a rel="next" id="more" href="#" class="round more">' + _('more') + '</a>');
					} catch(e){
						console.log(e);
					}
				}.pBind(this),'jsonp');
			} catch(e){
				console.log(e);
			}
			this.nest.find('.grid_refresh').addClass('loading');
		}
	});

	$('.wrapper .section').prepend('<div id="externalWindow" style="display:none"><iframe id="externalContentHolder" width="100%" height="100%" name="externalContentHolder"/><input class="round-btn" id="externalWindow_close" type="button" value="Close" /></div>');
    $('.spellcheckSubmit').click(function (e) {
        setTimeout("popup('externalWindow','show')", 1);
        var target = '#status';
        if ($('body').attr('id') == 'direct_messages' || $('body').attr('id') == 'inbox' || $('body').attr('id') == 'sent') {
            target = '#direct_message_form #text';
        }
        $('#spellcheck_content').val(($(target).val()));
        $('#spellcheck_form').submit();
        return false;
    });
    $('#externalWindow_close').click(function () {
        popup('externalWindow', 'hide')
    });
    $('.tinyTextSubmit').click(function (e) {
        try {
            var target = '#status';
            if ($('body').attr('id') == 'direct_messages'|| $('body').attr('id') == 'inbox' || $('body').attr('id') == 'sent') {
                target = '#direct_message_form #text';
            }
            $(target).val($(target).val().replace(/([,.?'()])[ ]/gim, "$1"));
			var target = $(target).val().replace(/([,.?'()])[ ]/gim, "$1");
			var urlRegex = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/g;
			var tinyRegex = /http:\/\/bit.ly|http:\/\/j.mp|http:\/\/tinyURL/ig;
			var result = target.match(urlRegex);
			var _urlStr = '';
			for (var i = 0 ; i < result.length; i++) {
				var _url = result[i];
				if (_url.length > 18 && !tinyRegex.test(_url)) {
					_urlStr += '&longUrl='+ encodeURIComponent(_url);
				}
			}
			if (_urlStr != '') { 
				$.getJSON(tinyURL+_urlStr+'&callback=?', function(result){
					var target = '#status';
					if ($('body').attr('id') == 'direct_messages' ||$('body').attr('id') == 'inbox' || $('body').attr('id') == 'sent') {
						target = '#direct_message_form #text';
					}
					for(var name in result.results){
						$(target).val($(target).val().replace(name, result.results[name].shortUrl));		
						Links.add({original:name, tinyURL:result.results[name].shortUrl});
					}
				})
			}
        } catch(e) {
            console.log(e);
            return false;
        }
        return false;
    });

	Preview = function(){
		var previews = {};

		Preview.init = function(){

		}
		Preview.base = function(service, url) {
			var exp = new RegExp(service.replace('.','\\.') + '/([a-zA-Z0-9]{6})$');
			var t = url.match(exp);
			if(t && t.length > 0)
				return 'http://' + service + '/show/thumb/'+t[1];
			return false;
		}
		Preview.youtube = function(url,size,shorten){
			if(url === null){ return ""; }
				size = (size === null) ? "big" : size;
				var vid;
				var results;
				results = shorten ? url.match(/\/([^\/]+)$/) : url.match("[\\?&]v=([^&#]*)");
				vid = ( results === null ) ? url : results[1];
			if(size == "small"){
				return "http://img.youtube.com/vi/"+vid+"/2.jpg";
			}else {
				return "http://img.youtube.com/vi/"+vid+"/0.jpg";
			}
		}
		Preview.flickr = function(url){
			var t = url.match(/flic\.kr\/p\/(.+)/);
			if(t && t.length > 0)
				return 'http://flic.kr/p/img/'+t[1]+'_t.jpg';
			return false;
		}
		Preview.tweetphoto = function(url){
			return 'http://tweetphotoapi.com/api/TPAPI.svc/imagefromurl?size=thumbnail&url='+url;
		}
		Preview.yfrog = function(url){
			var t = url.match(/yfrog\.com\/(.+)$/);
			if(t && t.length > 0)
				return 'http://yfrog.com/'+t[1]+'.th.jpg';
			return false;
		}
		Preview.refresh = function(parent){
			if(!Setting.get('preview').value)
				return false;
			var target = parent ? $('.tweet-url.web', parent) : $('.tweet-url.web');

			target.each(function(i, obj){
				var $this = $(obj);
				
				if($this.hasClass('isPreviewed'))
					return obj;
				$this.addClass('isPreviewed',true);
				var $parent = $($this.parents('li.status')[0]);
				var url = $this.attr('href');
				var preview = false;
				var purl = null;
				if(url.indexOf('twitpic.com')>-1){
					purl = Preview.base('twitpic.com', url);
				} else if(url.indexOf('youtube.com')>-1){
					purl = Preview.youtube(url,'small',false);
				} else if(url.indexOf('youtu.be')>-1){
					purl = Preview.youtube(url,'small',true);
				} else if(url.indexOf('flic.kr')>-1){
					purl = Preview.flickr(url);
				} else if(url.indexOf('yfrog.com')>-1){
					purl = Preview.yfrog(url);
				} else if(url.indexOf('tweetphoto.com')>-1){
					purl = Preview.tweetphoto(url);
				} else if(url.indexOf('img.ly')>-1){
					purl = Preview.base('img.ly', url);
				} else if(url.indexOf('spic.kr')>-1){
					purl = Preview.base('spic.kr', url);
				}

				if(purl){
					$this.attr({'title': "<img src='" + purl + "' alt='' />"});
					$('<img class="preview_thumb" src="data:image:png;base64,/9j/4AAQSkZJRgABAQEASABIAAD/7QBAUGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAACQcAVoAAxslRxwCAAACAAIcAkYAEFBpeGVsbWF0b3IgMS41LjH/4QCqRXhpZgAATU0AKgAAAAgABgESAAMAAAABAAEAAAEaAAUAAAABAAAAVgEbAAUAAAABAAAAXgEoAAMAAAABAAIAAAExAAIAAAARAAAAZodpAAQAAAABAAAAeAAAAAAAAABIAAAAAQAAAEgAAAABUGl4ZWxtYXRvciAxLjUuMQAAAAOgAQADAAAAAf//AACgAgAEAAAAAQAAABCgAwAEAAAAAQAAAA4AAAAA/9sAQwACAgICAgECAgICAgICAwMGBAMDAwMHBQUEBggHCAgIBwgICQoNCwkJDAoICAsPCwwNDg4ODgkLEBEPDhENDg4O/9sAQwECAgIDAwMGBAQGDgkICQ4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4O/8AAEQgADgAQAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAwDAQACEQMRAD8A/UEnxXeeNLu207TJ4/DEGlxGC/03RLK8kkuBaxO0Q8xCTIZC4PmEAHksBXpXhfxjq0epQ6FP4f1Hw/8AvBOlvqOmRw7o5bpUYIY7qTbgzcZXGFxniuH+LnhrQPFfj37NrGqa/pk+nXEkkP8AZ8UbpL51tbL+8DsMgeUeMdwcgiu68AWEOp28UdxrOr6rPpVtbo15dWtvDLcYuJZlVtgOFGIx8pBbZlix5qcXiJ16kVGPJyJJ6K0tFru23ve9tdr3PncLHFQxlSDT5N1JyTT7q26t09D/2Q==" width="16" height="14" alt="" />').insertAfter($this);
					$this.tipsy({gravity: 'n', additionalCSSClass:'preview'});

					previews[purl] = new Image();
					previews[purl].src = purl;
				}
			})
		}
	}
	Preview();
	Reply = function(){
		Reply.countLimit = 10;
		Reply.count = 0;
		Reply.color = [['#ffefef', '#ff9999'],['#f2efff','#ac99ff'],['#effffb','#99ffe5'], ['#fffdef', '#fff199'],['#fffdef', '#fff199'], ['#eff2ff', '#99acff'], ['#ffeffe', '#ff99f8'], ['#f4efff', '#b999ff'], ['#efffef', '#99ff99'], ['#effdff', '#99f3ff'], ['#fffcef', '#ffde4c']];
		Reply.user = null;
	
		Reply.init = function(){
			$('a.replyReply').live('click', function(){
				Reply.count = 0;
				$(this)[0].blur();
				Reply.open($(this), true);
				return false;
			});
			$('#results_update').livequery('click', function(){
				Reply.refresh();
			})

			$(page).watch("isTimelineChange", function(propertyName, oldValue, newValue) {
				if(!newValue){
					Reply.refresh();
				}
			})
			$('#pagination').live('click', function(){
				setTimeout('Reply.checkNewPage(0)', 500);
			});
			Reply.checkNewPage = function(i){
				if(i<100 && $('#pagination #more').hasClass('loading')){
					setTimeout('Reply.checkNewPage('+(++i)+')', 500);
				} else {
					Reply.refresh();
				}
			}
			
			Reply.moreMenu();
			Reply.refresh();
		}
		Reply.open = function(self, relay){
			if(++Reply.count > Reply.countLimit){
				Reply.count = 0;
				return false;
			}
			self.text('loading....');
			if($('body').attr('id') != 'show'){
				var nest = $(self.parents('li')[0]);
				var b = nest.css('background-color');
				if(nest.hasClass('focus') || b == 'transparent' || b == 'rgb(247, 247, 247)'){
					var color = Reply.color[Math.floor(Math.random()*(Reply.color.length))]
					nest.css('background-color', color[0]);
					nest.css('border-left', 'solid 2px '+color[1]);
				}
			} else {
				var nest = $(self.parents('.hentry.status')[0]);
			}
			var href = self.attr('href');
			$.ajax({
				url:href,
				type:'GET',
				dataType:'json',
				success:function(e){
					var color = color;
					content = text2Tweet(e.text);
					var m = ['Jan','Feb','Mar','Apr','May','June', 'Jul', 'Aug','Sep', 'Oct','Nov', 'Dec']
					var d = new Date(Date.parse(e.created_at));
					var t = (d.getHours()%12)+':'+d.getMinutes()+' '+(d.getHours()>12 ? 'PM' : 'AM')+' '+m[d.getMonth()]+' '+d.getDate()+'th';
					var k = Math.ceil(Math.random()*900000)

					if($('body').attr('id') != 'show'){
						var str = '\
					<li id="status_'+e.id+'" class="hentry u-'+e.user.screen_name+' status replyReply key_'+k+'" style="background-color:'+nest.css('background-color')+'; border-left:solid 2px '+nest.css('border-left-color')+';">\
						<span class="thumb vcard author">\
							<a class="tweet-url profile-pic url" href="/'+e.user.screen_name+'">\
								<img width="48" height="48" src="'+e.user.profile_image_url+'" class="photo fn" alt="'+e.user.name+'"/>\
							</a>\
						</span>\
						<span class="status-body">\
							<strong>\
								<a title="'+e.user.name+'" class="tweet-url screen-name" href="/'+e.user.screen_name+'">'+e.user.screen_name+'</a>\
							</strong>\
						<span class="actions">\
							<div>\
								<a title="favorite this tweet" id="status_star_'+e.id+'" class="fav-action non-fav">  </a>\
							</div>\
						</span>\
						<span class="entry-content">'+content+'</span>\
							<span class="meta entry-meta">\
								<a rel="bookmark" class="entry-date" href="/'+e.user.screen_name+'/status/'+e.id+'">\
									<span data="{time:\''+e.created_at+'\'}" class="published timestamp">'+t+'</span>\
								</a>\
							'+ (e.in_reply_to_screen_name == null || e.in_reply_to_status_id == null ? '' : ('<a class="replyReply" href="/'+e.in_reply_to_screen_name+'/status/'+e.in_reply_to_status_id+'">in reply to '+e.in_reply_to_screen_name+'</a>'))+'\
						</span>\
							<ul class="actions-hover">\
								<li>\
									<span class="reply">\
										<span class="reply-icon icon"/>\
										<a href="/?status=@'+e.user.screen_name+'%20&amp;in_reply_to_status_id='+e.id+'&amp;in_reply_to='+e.user.screen_name+'">' + _('Reply') + '</a>\
									</span>\
								</li>\
								'+(e.user.screen_name == user ? '<li><span class="del"><span class="delete-icon icon"/><a title="delete this tweet" href="#">' + _('Delete') + '</a></span></li>' : '')+'\
							</ul>\
						</span>\
					</li>';
					} else {
						var str ='<div id="status_'+e.id+'" class="hentry -'+e.user.screen_name+' status">\
						<span class="status-body">\
							<span class="status-content">\
								<span class="actions">\
									<div>\
										<a title="favorite this tweet" class="fav-action non-fav" id="status_star_'+e.id+'">&nbsp;&nbsp;</a>\
									</div>\
								</span>\
								<span class="entry-content">\
									@<a rel="nofollow" href="/egoing" class="tweet-url username">'+e.user.name+'</a>\
									'+content+'\
								</span>\
							</span>\
							<span data="{}" class="meta entry-meta">\
								<a href="http://twitter.com/litbeebilly/status/'+e.id+'" rel="bookmark" class="entry-date"><span data="{time:\''+e.created_at+'\'}" class="published timestamp">'+t+'</span></a>\
								<a href="/'+e.in_reply_to_screen_name+'/status/'+e.in_reply_to_status_id+'" class="replyReply">in reply to '+e.in_reply_to_screen_name+'</a>\
							</span>\
							<ul class="actions-hover">\
								<li>\
									<span class="reply">\
										<span class="reply-icon icon"></span>\
										<a href="/?status=@'+e.user.screen_name+'%20&amp;in_reply_to_status_id='+e.id+'&amp;in_reply_to='+e.user.screen_name+'">' + _('Reply') + '</a>\
									</span>\
								</li>\
								<li>\
									<span class="retweet-link">\
										<span class="retweet-icon icon"></span>\
										<a href="#">' + ('Retweet') + '</a>\
									</span>\
								</li>\
							</ul>\
						</span>\
					</div>';
					}
					self.hide();
					str = $(str);
					Reply.refresh(str);
					Preview.refresh(str)
					nest.after(str);
					if(relay){
						var l = $('.key_'+k+' a.replyReply');
						if(l.length>0){
							Reply.open(l,true);
						}
					}
				}
			})
			return false;
		}
		Reply.moreMenu = function() {
			var menu = '\
				<ul class="more-contextual action-more-list">\
					<li class="reply-all"><span><a href="#" title="<div class=\'shortcut\'>Shortcut key: R as in R2D2</div>"><i></i>' + _('Reply all') + '</a></span></li>\
					<li class="comment-retweet"><span><a href="#" title="<div class=\'shortcut\'>Shortcut key: t as in Tatooine</div>"><i></i>' + _('Retweet with comment') + '</a></span></li>\
					<li class="translate"><span><a href="#" title="<div class=\'shortcut\'>Shortcut key: o as in Obi-Wan</div>"><i></i>' + _('Translate') + '</a></span></li>\
				</ul>';
			
			this.morePopup = $(menu);
			this.morePopup.css({visibility:'hidden'}).show();
			$(document.body).append(this.morePopup);
			this.morePopup.css({width:this.morePopup.width()+'px', visibility:'visible'}).hide();
			
			$('ul.action-more-list li.reply-all a').live('click', function(event) {
				Shortcut.replyAll($(event.target).closest('#profile_box').length ? '' : this.user, $(event.target).closest('.hentry'));
			}.pBind(this)).addTipsy({gravity: 'e'});
			$('ul.action-more-list li.comment-retweet a').live('click', function(event) {
				Shortcut.retweetWithQuote($(event.target).closest('#profile_box').length ? '' : this.user, $(event.target).closest('.hentry'))
			}.pBind(this)).addTipsy({gravity: 'e'});
			$('ul.action-more-list li.translate a').live('click', function(event) {
				this.morePopup.hide()
				var t = $(event.target).closest('li.hentry').find('span.entry-content');
				Translate.exec($(t[0]).text(),Setting.get('translate').translate_language, t);
				return false;
			}.pBind(this)).addTipsy({gravity: 'e'});
		}
		Reply.refresh = function(parent) {
			Preview.refresh(parent);
			if(window.is_PBTweet)
				return false;
			
			if (!$(document.body).hasClass('signin-island')) {
				var actions = parent ? parent.find('.actions-hover') : $('.actions-hover');
			
				actions.each(function(i, obj) {
					if (!$(obj).is(':has(.more-link)') && !$(obj).is(':has(.del)')) {
						$(obj).append('\
							<li>\
								<span class="more-link">\
									<span class="more-icon icon"></span>\
									<a href="#">' + _('etc...') + '</a>\
								</span>\
							</li>');
					}
				
					$(obj).find('.more-link').hover(function(event) {
						$(event.target).closest('span.more-link').append(this.morePopup);

						this.user = $(event.target).closest('span.status-body').find('strong .screen-name').text();
						var offset = $(event.target).closest('li').offset();

						if ($(event.target).closest('#profile_box').length) {
							var top = offset.top + $(event.target).closest('.actions-hover').height() - $(document.body).scrollTop();
							var right = $(document.body).width() - (offset.left + $(event.target).closest('li').width() - $(document.body).scrollLeft()) - 7;

							this.morePopup.css({top:top + 'px', right: right + 'px'}).show();
						} else {
							this.morePopup.css({top: 'auto', right:'-7px', left:'auto'}).show();
						}

						event.preventDefault();
					}.pBind(this), function(event) {
						this.morePopup.hide();
						$(document.body).append(this.morePopup);
					}.pBind(this))
					
					$(obj).find('.more-link a').click(function(event) {
						event.preventDefault();
						event.stopPropagation();
					});
				
					if ($(obj).is(':has(.del)'))
						$(obj).find('li .del a').attr('title', '<div class=\'shortcut\'>Shortcut key: D as in Deathstar</div>').addTipsy({gravity:'e'});
				
					if ($(obj).is(':has(.reply)'))
						$(obj).find('li .reply a').attr('title', '<div class=\'shortcut\'>Shortcut key: r as in Rex</div>').addTipsy({gravity:'e'});
					
					if ($(obj).is(':has(.replydm)'))
						$(obj).find('li .replydm a').attr('title', '<div class=\'shortcut\'>Shortcut key: d as in Darth Vader</div>').addTipsy({gravity:'e'});
				}.pBind(this));
			}
			
			var target = parent ? parent.find('.meta.entry-meta') : $('.meta.entry-meta');

			target.each(function(){
				var as =$(this).find('a');
				for(var i = 0 ; i < as.length; i++){
					var v = $(as[i]).text();
					if(v.indexOf('in reply to')>-1 || v.indexOf('宛')>-1 || v.indexOf('en respuesta a')>-1){
						$(as[i]).addClass('replyReply');
					}
				}

			});
		}
		Reply.init();
	}
	var layout = new Layout();
	Reply();

	Profile = function(){
		this.__construct();
	};

	jQuery.extend(Profile.prototype, {
		onceloaded: false,
		onloading: false,
		
		profile: null,
		user: null,
		userid: null,
		lists: null,
		screen_name: null,
		buffers: {},
		
		_indicator: null,
		_image: null,
		_info: null,
		_userActions: null,
		_container: null,
		_head: null,
		_timeline: null,
		_direct: null,
		_menu: null,
		_style: $('<style type="text/css">.inline-form.retweet-dlg{z-index: 1000000 !important}</style>'),
		
		_tweets_tab: null,
		_mention_tab: null,
		_favorites_tab: null,
		_lists_tab: null,
		
		_buttons: {},
		
		template: '\
			<div id=\"profile_box\" class=\"dialog\">\
				<table>\
					<tbody>\
						<tr class="info">\
							<td class="info_layout">\
								<div class="wrap"><img src="" alt="" /></div>\
								<div class="info"></div>\
							</td>\
							<td class="tweet_layout">\
								<ul class="tabMenu">\
									<li id="tweets_tab"><a href="http://twitter.com">' + _('Tweets') + '</a></li>\
									<li id="mention_tab"><a href="http://twitter.com/#replies"></a></li>\
									<li id="favorites_tab"><a href="http://twitter.com/#favorites">' + _('Favorites') + '</a></li>\
									<li id="lists_tab"><a href="http://twitter.com/#lists">' + _('Lists') + '</a></li>\
								</ul>\
								<div id="tweets">\
									<div class="head">\
										<a id="list_direct_link" href="#"></a><ul class="more-contextual"></ul>\
									</div>\
									<div id="tweets_body">\
										<ol id="timeline" class="statuses"></ol>\
										<div class="pagination"></div>\
									</div>\
								</div>\
								<div class="user-actions">\
									<strong></strong>\
									<ul></ul>\
								</div>\
							</td>\
						</tr>\
						<tr class="suspected">\
							<td>This user\'s suspected.</td>\
						</tr>\
						<tr>\
							<td colspan="2" class="controls">\
								<div class="following-controls"></div>\
								<div class="actions">\
									<button class="btn" id="unfollowing_btn">' + _('Unfollow') + '</button>\
									<button class="btn" id="direct_message_btn">' + _('Direct Message') + '</button>\
									<button class="btn" id="reply_btn">' + _('Reply') + '</button>\
									<button class="btn" id="lists_btn">' + _('Manage in list') + '</button>\
									<button class="btn close_btn">' + _('Close') + '</button>\
								</div>\
							</td>\
						</tr>\
					</tbody>\
				</table>\
			</div>',

		__construct: function() {
			this.profile = $(this.template);
			
			this._indicator = new Image();
			this._indicator.src = srcURL + 'images/spinner.gif';
			
			this._image = $('td.info_layout div.wrap img', this.profile)
			this._info = $('td.info_layout div.info', this.profile);
			this._userActions = $('td.tweet_layout div.user-actions', this.profile).fadeOut();
			this._container = $('#tweets_body', this.profile);
			this._head = $('td.tweet_layout div.head', this.profile);
			this._timeline = $('ol', this._container);
			this._direct = $('#list_direct_link', this._head);
			this._menu = $('ul', this._head);
			
			this._tweets_tab = $('#tweets_tab', this.profile);
			this._mention_tab = $('#mention_tab', this.profile);
			this._favorites_tab = $('#favorites_tab', this.profile);
			this._lists_tab = $('#lists_tab', this.profile);
			
			this._buttons.unfollow = $('#unfollowing_btn', this.profile);
			this._buttons.dm = $('#direct_message_btn', this.profile);
			this._buttons.reply = $('#reply_btn', this.profile);
			this._buttons.list = $('#lists_btn', this.profile);
			
			$('#content').append(this.profile.hide());
			
			this.initialize();
		},
		initialize: function() {
			$('td.info_layout, ul.tabMenu, td.controls', this.profile).wheel(function(event) {
				event.stopPropagation();
				event.preventDefault();
			});
			
			$('.list_checkbox', this.profile).live('click', function(event) {
				var chkbox = $(event.target).hide();
				var data = eval('('+unescape(chkbox.attr('data'))+')');
				var indicator = chkbox.prev().css('display', 'inline-block');
				
				$.ajax({
					type: chkbox.attr('checked') ? 'POST' : 'DELETE',
					dataType: 'json',
					url: 'http://twitter.com' + data.uri + '/members' + (chkbox.attr('checked') ? '' : '/' + this.userid),
					data: {
					    authenticity_token: twttr.form_authenticity_token,
                	    twttr: true,
						'member[id]': this.userid
                	},
					complete: function() {
						indicator.hide();
						chkbox.css('display', 'inline-block');
					},
					error: function() {
						chkbox.checked = !chkbox.checked;
					},
					success: function(){
						this.buffers[this.user].actions = this._userActions.find('li');
					}.pBind(this)
				})
			}.pBind(this));
			
			this._buttons.list.toggle(function() {
				this._userActions.fadeIn();
			}.pBind(this), function() {
				this._userActions.fadeOut();
			}.pBind(this));
			
			$('td.controls .close_btn', this.profile).click(function() {
				this.close();
			}.pBind(this));
		
			$('ul.tabMenu li a', this.profile).click(function(event) {
				if (this.onloading)
					return false;
				
				this.loadRecentTweets(1, null, $(event.target).parent().attr('id'));
				$(this).blur();
			
				event.preventDefault();
			}.pBind(this));
			
			$('ul.actions-hover li .retweet-link', this.profile).live('click', function() {
				$('.inline-form.retweet-dlg').css('z-index', 1000000);
			}.pBind(this));
			
			this._container.wheel(function(event, delta) {
				var height = parseInt($(this).height());
				var top = parseInt($(this).scrollTop());
				delta = delta > 0 ? 'up' : 'down';
				
				if ((delta == 'down' && (height + top) >= (this.scrollHeight - 5)) || (delta == 'up' && top == 0)) {
					event.stopPropagation();
					event.preventDefault();
				}
			});
			
			this._head.hover(function(event) {
				var offset = this._direct.position();
				this._menu.css({top:offset.top + this._direct.outerHeight() + 'px', left:offset.left + 'px'}).show();
				if (this._direct.parent().width() > this._menu.width())
					this._menu.css('width', this._direct.parent().width() + 10 + 'px');
			}.pBind(this), function() {
				this._menu.hide();
			}.pBind(this));
			
			$('#unfollowing_btn, #follow-btn', this.profile).live('click', function(event) {
				var obj = $(event.target);
				
				switch(obj.attr('relation')){
				case 'friend':
					Friends.destroy(this.user, function() {
						this.setRelation('follower');
						$("#home_tab .in-page-link", this.profile).trigger('click');
					}.pBind(this));

					break;
				case 'following':
					Friends.destroy(this.user, function() {
						this.setRelation('none');
						$("#home_tab .in-page-link", this.profile).trigger('click');
					}.pBind(this));

					break;
				case 'follower':
					Friends.create(this.user, function() {
						this._save('sees_retweets', true);
						this.setRelation('friend');
						$("#home_tab .in-page-link", this.profile).trigger('click');
					}.pBind(this));

					break;
				case 'none':
					Friends.create(this.user, function() {
						this._save('sees_retweets', true);
						this.setRelation('following');
						$("#home_tab .in-page-link", this.profile).trigger('click');
					}.pBind(this));

					break;
				case 'protected':
				case 'requested_protected':
					$('#request_protect_form', this.profile).submit();

					break;
				}
				
				event.preventDefault();
			}.pBind(this));
			
			this._buttons.dm.click(function(event){
				switch($(event.target).attr('relation')){
					case 'friend':
					case 'following':
					case 'follower':
						location.href = '/direct_messages/create/' + this.user;
						break;
					case 'none':
						(new InfoNotification()).setMessage(_("Sorry, you can't send direct message.")).show();
						break;
				}
			}.pBind(this))
			
			this._buttons.reply.click(function() {
				location.href = '/?status=' + escape('@' + this.user);
			}.pBind(this));
			
			$('a.screen-name.timestamp-title, span.screenname a, #following .photo.fn, .thumb.vcard.author .photo.fn, .conv_chain .icons img, .tweet-url.profile-pic img, .side_thumb.photo.fn, .tweet-url.username, .tweet-url.screen-name, .vcard .photo.fn, .thumb.vcard a, .author a').live('click', function(event) {
				var rex = new RegExp('(^\/|https?:\/\/twitter\.com\/)(.+)');
				
				try {
					var username = $(event.target).parent().attr('href').match(rex)[2];
				} catch(e) {
					try {
						var username = $(event.target).attr('href').match(rex)[2];
					} catch(e) {}
				}
				
				if (!!twttr.HOVERCARD)
					twttr.HOVERCARD.hide();

				this.user = username;
				this.open();
				
				event.preventDefault();
				event.stopPropagation();
			}.pBind(this)); 
			
			$('.in-page-link, #tweets .reply').live('click', function() {
				this.close();
			}.pBind(this));
			
			$(window).resize(function() {
				this.onceloaded = false;
				this.repaint();
			}.pBind(this))
		
			$(window).resize(function () {
				this.repaint();
			}.pBind(this));
		},
		open: function(){
			this._container.scrollTop(0);
			this._image.attr('src', this._indicator.src);
			this._image.css({width:'auto', height:'auto', margin:0, display:'inline'});
			this._image.parent().css('line-height', '220px');
			$('td.controls div.following-controls', this.profile).html('');
			this._buttons.unfollow.hide();
			this._buttons.dm.hide();
			this._buttons.reply.hide();
			this._buttons.list.hide();
			this._userActions.hide();
			
			this._mention_tab.hide();
			this._favorites_tab.hide();
			this._lists_tab.hide();
			
			this.profile.find('tbody tr.info').show()
			this.profile.find('tbody tr.suspected').hide();
			$('head').append(this._style);
			this.set();
			curtain.drop(this.close.pBind(this));
		},
		close: function(){
			this.user = null;
			this.profile.hide();
			this._style.remove();
			this._userActions.fadeOut();
			this._container.scrollTop(0);
			this._info.text('');
			curtain.lift();
		},
		set: function(){
			this.profile.show();
			
			this.repaint();
			this.loadInfo();
			this.loadRecentTweets(1, null);
		},
		loadInfo: function() {
			try {
				this.loadInfo.comm.abort();
			} catch(e) {}
		
			this._info.parent().addClass('loading');
			this.onloading = true;
			this._userActions.find('strong').text(replaceParams(_('Manage %{screen_name} in your list:'), {screen_name:this.user}));
			this._mention_tab.find('a').text('@'+this.user);
			
			if (!!this.buffers[this.user]) {
				this._info.html(this.buffers[this.user].info);
				this._calcImageSize(this.buffers[this.user].pict);	
				this._userActions.find('ul').html('').append(this.buffers[this.user].actions);
				
				var r = this.calcRelation();
				
				this.setRelation(r);
				this._info.parent().removeClass('loading');
				this.onloading = true;
			} else {
				this.loadInfo.comm = $.ajax({
					type: "GET",
					url: '/' + this.user,
					success: function(html) {
						if (html.match('Twitter / Suspended')) {
							this.profile.find('tbody tr.info').hide()
							this.profile.find('tbody tr.suspected').show();
						} else {
							try {
								var $html = $(html);
								var isfriend = $html.find('div.user').hasClass('direct-messageable');
								var isfollowing = $html.find('div.user').hasClass('following');
								var isProtected = $html.find('.protected-box').length > 0;
								var isRequestFollowing = (!isfollowing && isProtected &&$html.find('#cancel_request').length) > 0;
								var r = 'nothing';
								var buffer = {};
							
								this.lists = [];
							
								$html.find('.sidebar-menu.lists-links li a').each(function(i, obj) {
									this.lists.push(eval('('+$(obj).attr('data')+')'));
								}.pBind(this));

								if (this.lists.length == 0) {
									if (this._lists_tab.is(':visible'));
										this._lists_tab.hide();
								} else {
									this._lists_tab.show();
								}

								this._head.hide()
								this._menu.html('').hide();

								for (var i=0; i<this.lists.length; i++) {
									var node = $('<li><a href="#"><i></i>' + this.lists[i].slug + '</a></li>');
									node.click(this.loadList.pBind(this));

									this._menu.append(node);

									if (i == 0) {
										this._direct.html(this.lists[i].slug + '<i class="arrow"></i>');
										node.addClass('selected');
									}
								}
							
								if ($html.find('.block-sidebar-action a').length)
									this.userid = $html.find('.block-sidebar-action a').attr('href').match(/\d+/)[0];
								else
									this.userid = $html.find('#profile-image').attr('src').match(/\/profile_images\/([0-9]+)\//)[1];
								
								var src = $html.find('#profile-image, .profile-img').attr('src').replace(/(_normal|_mini|_bigger)\.(gif|jpg|jpeg|png)$/, '.$2');
								var image = new Image();
								image.onload = function() {
									this._calcImageSize(image);
								}.pBind(this);
								image.src = src;
								buffer.pict = image;
							
								this._save('avatar_src', src);
								this._save('user_id', this.userid);
								this._save('is_protected', isProtected);
								this._save('do_you_follow', isfollowing);
								
								var r = this.calcRelation()
								this.setRelation(r);
								
								var result = {};
							
								result.screen_name = this.user;
								result.website_url = $html.find('.about.vcard.entry-author li a.url').attr('href') || null;
								result.website_text = $html.find('.about.vcard.entry-author li a.url').text() || null;
								result.location = $.trim($html.find('.about.vcard.entry-author li span.adr').text());
								result.description = $.trim($html.find('.about.vcard.entry-author li span.bio').text());
								result.full_name = $html.find('.about.vcard.entry-author li span.fn').text();
								result.following_count = $html.find('#following_count').text();
								result.follower_count = $html.find('#follower_count').text();
								result.lists_count = $html.find('#lists_count').text();
								result.tweet_count = $html.find('#update_count').text();
								result.verified = $html.find('#profile li.verified-profile').length;
							
								this._save('screen_name', this.user);
								this._save('description', result.description);
								this._save('location', result.location);
								this._save('full_name', result.screen_name);
								this._save('following_count', result.friends_count);
								this._save('follower_count', result.followers_count);
								this._save('lists_count', result.list_count);
								this._save('tweet_count', result.statuses_count);
								this._save('website_text', result.url);
								this._save('website_url', result.url);
								this._save('is_you', user == this.user);
								
								var _location = !result.location ? '' : '<li class="location">' + result.location + '</li>';
								var _url = result.website_url == null ? '' : '<li class="web"><strong>' + _('Web:') + ' </strong><a target="_blank" href="' + result.website_url + '">' + result.website_text + '</a></li>';
								var _description = !result.description ? '' : '<li class="bio"><strong>' + _('Bio:') + ' </strong>' + result.description + '</li>';
								var str = '\
									<ul class="user_stats">\
										<li class="first">\
											<strong class="stat"><a target="_blank" class="url" href="' + t + result.screen_name + '">' + result.tweet_count + '</a></strong>\
											<span class="type">' + _('tweets') + '</span>\
										</li><li>\
											<strong class="stat"><a target="_blank" href="' + t + result.screen_name + '/following">' + result.following_count + '</a></strong>\
											<span class="type">' + _('following') + '</span>\
										</li><li>\
											<strong class="stat"><a target="_blank" class="url" href="' + t + result.screen_name + '/followers">' + result.follower_count + '</a></strong>\
											<span class="type">' + _('followers') + '</span>\
										</li><li class="last">\
											<strong class="stat"><a target="_blank" class="url" href="' + t + result.screen_name + '/lists/memberships">' + result.lists_count + '</a></strong>\
											<span class="type">' + _('lists') + '</span>\
										</li>\
									</ul>\
									<ul class="about vcard entry-author">\
										<li class="username"><strong><a target="_blank" href="' + t + result.screen_name + '">' + result.screen_name + '</a></strong>' + (result.verified ? '<a class="verified" href="/help/verified"><em>Verified Account</em></a>' : '') + '</li>\
										<li class="screen-name">' + result.full_name + '</li>\
										' + _location + '\
										' + _url + '\
										' + _description + '\
									</ul>';

								this._info.html(str);
								buffer.info = str;
								
								var _listTags = [];

								$(html).find('ul.list-tags li a').each(function() {
									_listTags.push(eval("(" + $(this).attr('data') + ")"))
								});

								var li = '';
								var lis = $('.sidebar-menu.lists-links li');

								for (var i=0; i<lis.length; i++) {
									$this = $(lis[i]);

									var d = eval("(" + $this.find('a').attr('data') + ")");
								
									if (!d.full_name.match(new RegExp('@' + user + '\/')))
										continue;
								
									var flag = false;

									for (var j=0; j<_listTags.length; j++) {
										if (_listTags[j].id == d.id) {
											flag = true;
											break;
										}
									}
								
									li += '<li><img class="spinner" src="" style="display: none;" alt="" title="waiting" height="14" width="14" />\
										<input type="checkbox" id="list_'+d.id+'" class="list_checkbox" data="'+escape($this.find('a').attr('data'))+'"'+(flag?' checked="checked" ' : '')+' />\
										<label for="list_'+d.id+'">'+d.name+'</label>\
									  </li>';
								}
								
								this._userActions.find('ul').html(li);
								buffer.actions = li;
							
								this._info.parent().removeClass('loading');

								this.buffers[this.user] = buffer;
							} catch(e) {
								//console.log(e);
							}
						}
					}.pBind(this)
				});
			}

		},
		loadList: function(event) {
			if (this.onloading)
				return false;
			
			this._menu.hide();
			
			var current = $(event.target);
			var text = current.text();
			current.parent('li').siblings().removeClass('selected');
			current.parent('li').addClass('selected');
			
			this._direct.attr('href','/' + this.user + '/' + text).html(text + '<i class="arrow"></i>');
			this.loadRecentTweets(1, null, 'lists_tab', current.text());
			
			event.preventDefault();
			event.stopPropagation();
		},
		loadRecentTweets: function(page, max_id, mode, extra_id) {
			this.onloading = true;
			
			if (page == 1) {
				this._container.find('.pagination').hide();
				this._timeline.html('');
			}
			
			if (this.loadRecentTweets.comm != undefined)
				this.loadRecentTweets.comm.abort();
		
			if (mode == 'lists_tab' && this['_lists_tab'].is(':visible'))
				this._head.show();
			else
				this._head.hide();
			
			this.repaint();
			
			var max_aux = max_id == undefined ? '' : '&max_id=' + max_id;
			
			if (mode == undefined)
				mode = 'tweets_tab';
			
			$('#paginationProfile .more', this.profile).addClass('loading').text('');
			$('ul.tabMenu li', this.profile).removeClass('active');
			
			switch (mode) {
			case 'mention_tab':
				var url = 'http://search.twitter.com/search.json?q=@' + this.user + '&rpp=20&maxId=' + max_aux + "&page=" + page;
				var type = 'jsonp';
				break;
			case 'favorites_tab':
				var url = "/favorites?page=" + page + "&twttr=true&user=" + this.user + max_aux;
				var type= 'json';
				break;
			case 'lists_tab':
				var url = '/' + this.user + '/' + this._head.find('li.selected').text() + (max_id == null ? '' : '?max_id=' + max_id + "&page=" + page + '&twttr=true');
				var type= 'json';
				break;
			default:
				var url = "/" + this.user + "?page=" + page + "&twttr=true" + max_aux;
				var type= 'json';
				break;
			}
			
			this['_' + mode].addClass('active loading');
			this._container.removeClass().addClass(mode);
			
			this.loadRecentTweets.comm = $.get(url,{},function (json) {
                    try {
						var timeline = '';
						
						$('#paginationProfile .round.more', this.profile).removeClass('loading');
						this._container.find('.pagination').show();
				
						switch (mode) {
						case 'mention_tab':
							var m = ['Jan','Feb','Mar','Apr','May','June', 'Jul', 'Aug','Sep', 'Oct','Nov', 'Dec'];
						
							for (var i=0; i<json.results.length; i++){
								try{
									var result = json.results[i];
									var d = new Date(Date.parse(result.created_at));
									var t = (d.getHours()%12)+':'+d.getMinutes()+' '+(d.getHours()>12 ? 'PM' : 'AM')+' '+m[d.getMonth()]+' '+d.getDate()+'th';
						
									result['text'] = result['text'].replace(/@(\w+)/g,'<a href="/$1" class="tweet-url username">@$1</a>');
									result['text'] = result['text'].replace(/#(\w+)/g,'<a class="tweet-url hashtag" title="#$1" href="/search?q=%23$1">#$1</a>');
									result['text'] = result['text'].replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,"<a href=\"$1\" target=\"_blank\">$1</a>");
								
									timeline += replaceParams(PanelSearches.prototype.body, {
										actions:result['from_user'] == user ? PanelSearches.prototype.actions.you : PanelSearches.prototype.actions.other,
										id: result['id'],
										from_user: result['from_user'],
										profile_image_url: result['profile_image_url'],
										text: result['text'],
										time: t
									});
								} catch(e){
									console.log(e);
								}
							}
				
							nextpage = json.page+1;
							max_id = json.max_id;
							timeline = $(timeline);
						
							var button = $('<div id="paginationProfile"><div class="round more">' + _('more') + '</div></div>');
							button.click(function() {
								this.loadRecentTweets(nextpage, max_id, mode);
							}.pBind(this));
					
							break;
						default:
							if (json['#pagination'] != null) {
								var p = json['#pagination'].match(/max_id=(\d+)&amp;page=(\d{1,})/);
								var max_id = p[1];
								var nextpage = p[2];
								var button = $('<div id="paginationProfile"><div class="round more">' + _('more') + '</div></div>');
								button.click(function() {
									this.loadRecentTweets(nextpage, max_id, mode);
								}.pBind(this));
							
								$('#paginationProfile', this.profile).remove();
							} else {
								button = '';
							}
							
							timeline = $(json['#timeline']).html();
								
							if (mode == 'tweets_tab' && page == 1)
								this._save('latest_status', $(timeline).find('li.hentry:first span.entry-content').html());
							
							break;
						}
					
						this['_' + mode].removeClass('loading');
					
						this._timeline.append(timeline);
						this._timeline.find('li.hentry').addClass(mode);
						
						/*
						if (page > 1) {
							var p = this._timeline.find('li.status:last-child').position().top;
							this._container.animate({scrollTop:this._container.scrollTop() + p}, 500);
						}
						*/
						
						this._timeline.find('li.status:last-child').addClass('last');
						this._container.find('.pagination').show().html(button);
						
						Reply.refresh(this._timeline);
						$.Statuses.initialize(this._timeline);
						
						this.onloading = false;
					} catch(e) {
                        //console.log(e);
						this.onloading = false;
                    }
					
					this.repaint();
				}.pBind(this),type);
		},
		calcRelation: function() {
			var r = 'none';
			
			if (this._get('is_protected'))
				r = 'protected';
			else if (this._get('do_you_follow'))
				r = this._get('does_follow_you') ? 'friend' : 'following';
			
			return r;
		},
		setRelation: function(relation) {
			this._buttons.list.show();
			this._mention_tab.show();
			
			switch (relation) {
			case 'protected':
			case 'requested_protected':
				this._buttons.dm.hide();
			
				break;
        	}
			
			this._buttons.unfollow.attr('relation', relation);
			this._buttons.dm.attr('relation', relation);

			switch(relation){
			case 'friend':
			case 'following':
				if (relation == 'friend')
					this._buttons.dm.show();
				else
					this._buttons.dm.hide();
				
				this._buttons.reply.show();
				this._buttons.unfollow.show();
				this._buttons.unfollow.text(_('Unfollow'));
				this._favorites_tab.show();
				
				var wrap = $('<div class="wrap"><span class="is-following"></span><span class="you-follow-user">' + _('You follow') + '</span></div>');
				var share = $('<span title="Retweet Settings" class="setting shares-setting"></span>').addClass(this._get('sees_retweets') ? 'shares-setting-not-off' : 'shares-setting-off');
				share.click(function(event) {
					if ($(event.target).hasClass('shares-setting-not-off'))
						this._save('sees_retweets', false);
					else
						this._save('sees_retweets', true);
					twttr.HoverCard.followActionHandler(event.target, this.userid, this.user, true);
				}.pBind(this))
				$('td.controls div.following-controls', this.profile).html(wrap.append(share));
				
				break;
			case 'follower':
				this._buttons.dm.show();
				this._buttons.reply.show();
				this._buttons.unfollow.hide();
				this._favorites_tab.show();
				
				$('td.controls div.following-controls', this.profile).html($('<a id="follow-btn" href="/" class="a-btn user"><i></i>' + _('Follow') + '</a>').attr('relation', relation));
				
				break;
			case 'none':
				this._buttons.dm.hide();
				this._buttons.unfollow.hide();
				this._favorites_tab.show();
				
				if (this.user == user) {
					$('td.controls div.following-controls', this.profile).html('<div class="wrap"><span class="is-you">' + _('That\'t you') + '</span></div>');
					this._buttons.reply.hide();
				} else {
					$('td.controls div.following-controls', this.profile).html($('<a id="follow-btn" href="/" class="a-btn user"><i></i>' + _('Follow') + '</a>').attr('relation', relation));
					this._buttons.reply.show();
				}
				
				break;
			case 'protected':
				if (this.loadRecentTweets.comm != undefined) {
					this.loadRecentTweets.comm.abort();
					this.onloading = false;
					$('ul.tabMenu li', this.profile).isLoaded();
				}
				this._buttons.unfollow.text('Send following request');
				this._timeline.html('<li class="protected">This person has protected their tweets. You need to send a request before you can start following this person.<form method="post" id="request_protect_form" target="_blank" action="/friendships/create/'+this.user+'"><input type="hidden" value="'+twttr.form_authenticity_token+'" name="authenticity_token"/></form></li>');
			
				break;
			case 'requested_protected':
				if (this.loadRecentTweets.comm != undefined) {
					this.loadRecentTweets.comm.abort();
					this.onloading = false;
					$('ul.tabMenu li', this.profile).isLoaded();
				}
				this._buttons.unfollow.text('Go cancel following request');
				this._timeline.html('<li class="requested">Request sent. You\'ve sent a request to follow this person. If your request is approved, you\'ll be able to view their tweets.<form method="GET" id="request_protect_form"  target="_blank" action="'+this.user+'"></form></li>');
			
				break;
			case 'nothing':
				break;
			}
		},
		repaint: function() {
			try {
				if (this._lists_tab.hasClass('active'))
					this._container.css('top', '60px');
				else
					this._container.css('top', '34px');
				
				var bottom = 65;
				
				if ($('#banana').is(':visible'))
					bottom += $('#banana').outerHeight();
				 
				this.profile.css({
					left: ($(window).width() / 2 - this.profile.width() / 2) +'px',
					bottom: bottom + 'px'
				});
			} catch(e) {
				console.log(e);
			}
		},
		_calcSizeInBox: function(curWidth, curHeight, boxWidth, boxHeight, type) {
			var imgWidth, imgHeight, newWidth, newHeight, tempWidth, tempHeight;
			var enlarge = !!type;
			
			if (boxWidth == null && boxHeight == null)
				return false;

			if (!!boxWidth && !boxHeight) {
				if (curWidth > boxWidth) {
					newWidth = boxWidth;
					newHeight = Math.round(curHeight * newWidth / curWidth);
				} else {
					newWidth = curWidth;
					newHeight = curHeight;
				}
			} else if (!boxWidth && !!boxHeight) {
				if (curHeight > boxHeight) {
					newHeight = boxHeight;
					newWidth = Math.round(curWidth * newHeight / curHeight);
				} else {
					newWidth = curWidth;
					newHeight = curHeight;
				}
			} else {
				if (curWidth > boxWidth) {
					newWidth = boxWidth;
					newHeight = Math.round(curHeight * newWidth / curWidth);
				} else {
					newWidth = curWidth;
					newHeight = curHeight;
				}

				if (newHeight > boxHeight) {
					tempHeight = newHeight;
					newHeight = boxHeight;
					newWidth = Math.round(newWidth * newHeight / tempHeight);
				}
			}

			if (curWidth * curHeight > newWidth * newHeight) {
				if (enlarge) {
					imgWidth = curWidth;
					imgHeight = curHeight;
				} else {
					imgWidth = newWidth;
					imgHeight = newHeight;
				}
			} else if (curWidth * curHeight == newWidth * newHeight) {
				imgWidth = curWidth;
				imgHeight = curHeight;
			} else if (curWidth * curHeight < newWidth * newHeight) {
				if (enlarge) {
					imgWidth = newWidth;
					imgHeight = newHeight;
				} else {
					imgWidth = curWidth;
					imgHeight = curHeight;
				}
			}

			return {width: imgWidth, height: imgHeight};
		},
		_calcImageSize: function(image) {
			if (image.width > image.height) {
				var size = this._calcSizeInBox(image.width, image.height, null, 220);
			} else {
				var size = this._calcSizeInBox(image.width, image.height, 220, null);
			}

			this._image.parent().css('line-height', 'normal');
			this._image.attr('src', image.src);
			this._image.css({width:size.width + 'px', height:size.height + 'px', display:'block'});

			if (size.width > 220)
				this._image.css('margin-left', Math.floor((220 - size.width) / 2) + 'px');
			else
				this._image.css({marginLeft:'auto', marginRight:'auto'});

			if (size.height > 220)
				this._image.css('margin-top', Math.floor((220 - size.height) / 2) + 'px');
			else if (size.height < 220)
				this._image.css('margin-top', Math.floor((220 - size.height) / 2) + 'px');
		},
		_get: function(name) {
			return twttr.tweeters[this.user][name] || null;
		},
		_save: function(name, value) {
			if (!twttr.tweeters[this.user]) {
				twttr.tweeters[this.user] = {
					avatar_src: null,
					description: null,
					device_updates: false,
					do_you_follow: false,
					does_follow_you: true,
					follower_count: 0,
					following_count: 0,
					full_name: null,
					gets_device_updates: false,
					is_blocking: false,
					is_employee: false,
					is_logged_in: true,
					is_protected: false,
					is_verified: false,
					is_you: false,
					lang: "en",
					latest_status: null,
					lists_count: 0,
					location: null,
					replies: false,
					retweets: true,
					screen_name: null,
					sees_replies: false,
					sees_retweets: false,
					tweet_count: 0,
					user_id: null
				};
			}
			if (!twttr.tweeters[this.user][name])
				twttr.tweeters[this.user][name] = value;
		}
	});

	if (Setting.get('profile').value)
		profile = new Profile();

    $('#update-submit').click(function () {
        popup('externalWindow', 'hide');
    });

	$('#sign_out_link').click(function() {
        $.cookie(user + '_twitpic_auth', null);
    });

	Shortcut = function(){
		Shortcut.show;
		Shortcut.init = function(){
			if(Setting.get('shortcut').value != undefined && !Setting.get('shortcut').value){
				return true;
			}
			if($.cookie('shortcut_'+user) == null || $.cookie('shortcut_'+user) == '0'){
				$.cookie('shortcut_'+user,'0',{expires:3650, path:'/'});
				Shortcut.show = false;
			} else {
				$.cookie('shortcut_'+user,'1',{expires:3650, path:'/'});
				Shortcut.show = true;
			}
			$('div#following').after('\
			<div class="collapsible'+(Shortcut.show ? '' : ' collapsed')+'" id="shortcut_help">\
				<hr/><h2 id="ss_menu" class="sidebar-title"><span>Keyboard Shortcuts</span></h2>\
				<div id="shortcut" style="'+(Shortcut.show ? '' : 'display:none;')+'">\
					<table>\
						<tr><td class="key">?</td><td class="label">Shortcut Help</td></tr>\
						<tr><td class="key">i</td><td class="label">Edit Mode</td></tr>\
						<tr><td class="key">ESC</td><td class="label">Command Mode</td></tr>\
						<tr><td class="key">Alt+Enter</td><td class="label">Submit</td></tr>\
						<tr><td class="key">J</td><td class="label">Newer Tweet</td></tr>\
						<tr><td class="key">K</td><td class="label">Older Tweet</td></tr>\
						<tr><td class="key">D</td><td class="label">Delete Tweet</td></tr>\
						<tr><td class="key">R</td><td class="label">Reply All</td></tr>\
						<tr><td class="key">r</td><td class="label">Reply</td></tr>\
						<tr><td class="key">F</td><td class="label">Favorite</td></tr>\
						<tr><td class="key">t</td><td class="label">Retweet with comment</td></tr>\
						<tr><td class="key">a</td><td class="label">Refresh all panel</td></tr>\
						<tr><td class="key">O</td><td class="label">Translate</td></tr>\
						<tr><td class="key">h</td><td class="label">Move Home</td></tr>\
						<tr><td class="key">m</td><td class="label">Move @'+user+'</td></tr>\
						<tr><td class="key">d</td><td class="label">Move DM</td></tr>\
						<tr><td class="key">f</td><td class="label">Move Favorites</td></tr>\
						<tr><td class="key">s</td><td class="label">Focus search</td></tr>\
						<tr><td class="key">g</td><td class="label">Top</td></tr>\
						<tr><td class="key">G</td><td class="label">Bottom</td></tr>\
					</table>\
				</div>\
			</div>');
			$('#shortcut_help #ss_menu').live('click',function(){
				Shortcut.toggle();
			});
			$('#dm-submit, #status_update_form').bind('submit', function() {
				window.scrollTo(0, window.prevScrollTop);
			});
			$('ul.actions-hover li .reply').click(function() {
				window.prevScrollTop = $(window).scrollTop();
			});
			$(document.body).wheel(function(event, delta) {
				if (delta <= 0)
					window.prevScrollTop  = 0;
			});
			$(window).ready(function(){
				window.prevScrollTop  = 0;
				window.currentPosition = $('#timeline li:eq(0)');
			}).keyup(function(event){
				var _k = event.keyCode;
				var k = String.fromCharCode(event.keyCode);
				if((Setting.get('suggest').value=='1' && sugg.isActive()) || $('#status_login_box').hasClass('show'))
					return;
				switch (event.originalEvent.target.type) {
					case 'textarea':
					case 'text':
						switch (_k) {
							case 27: //ESC
								$('textarea').blur();
								$('input').blur();
								window.scrollTo(0, window.prevScrollTop);
								break;
							case 13:
								if(event.altKey){
									switch($('body').attr('id')){
										case 'inbox':
										case 'sent':
											$('#dm-submit').submit();
											break;
										default:
											$('#status_update_form').submit();
											break;
									}
								}
								break;
						}
						return;
					default:
						switch (_k) {
							case 27://ESC
								profile.close();
								break;
							case 73://I
								window.prevScrollTop = $(window).scrollTop();
								switch($('body').attr('id')){
									case 'inbox':
									case 'sent':
										$('.info #text').focus();
										break;
									default:
										$('.info #status').focus();
										break;
								}
								return;
							case 59://:
								if (event.shiftKey) {
									$('#command_view').show();
									$('#command_view').text(':');
								}
								break;
							case 191:
								if(event.shiftKey){
									Shortcut.toggle();
								}
								break;
						}
						/*
						if ($('#command_view').css('display') == 'block' && $('#command_view').text().indexOf(':') == 0) {
							$('#command_view').text($('#command_view').text() + k);
						}
						*/

						prevPressKeyEvent = event;

						switch (k) {
							case 'A':
								layout.refreshAll();
								break;
							case 'G':
								if (event.shiftKey) scrollTo(0, $(document).height())
								else if (prevPressKeyEvent.keyCode == 71 && !prevPressKeyEvent.shiftKey && !event.shiftKey)
									scrollTo(0, 0);
								break;
							case 'L':
								if (window.currentPosition.length != 1) break;
								profile.open(window.currentPosition.find('.tweet-url.screen-name').text())
								break;
							case 'H':
								if(!$("#home_tab .in-page-link").length){
									location.href='/';
								}
								$("#home_tab .in-page-link").click();
								break;
							case 'F':
								if (!event.shiftKey) {
									$("#favorites_tab .in-page-link").click();
								} else {
									var r = currentPosition.find('.fav-action');
									if(r.length>0){
										r.click();
									}
								}
								break;
							case 'D':
								if (!event.shiftKey) {
									$($("#direct_messages_tab .in-page-link")[0]).click()
								} else {
									var d = currentPosition.find('.del');
									if(d.length>0){
										d.click();
									}
									currentPosition = currentPosition.next();
								}
								break;
							case 'M':
								$("#replies_tab .in-page-link").click();
								break;
							case '1':
							case '2':
							case '3':
							case '4':
							case '5':
							case '6':
							case '7':
							case '8':
							case '9':
								if(!event.altKey && !event.ctrlKey && !event.shiftKey){
									var t = Tab.$tabMenuNest.find('li').get(k-1);
									if(t) {
										Config.Layout.set('tabsActive', $(t).attr('index'));
										Tab.change(Config.Layout.get('tabsActive'));
										var i = Number(Tab.$tabMenuNest.find("li").index($('li.active',Tab.$tabMenuNest)));
										if($('li.active',Tab.$tabMenuNest).attr('index') == Config.Layout.get('tabsActive') && layout.$grid_layout_tr.find('td.tdnest').length-1 == Config.Layout.get('tabs.' + i + '.panels').length){
											layout.refreshAll();
											return false;
										}
										Tab.change(Config.Layout.get('tabsActive'));
									}
								}
								break;
							case 'S':
								$('#sidebar_search_q').focus();
								break;
							case 'R':
								if (event.shiftKey) {
									var host = currentPosition.find('.tweet-url.screen-name').text();
									Shortcut.replyAll(host, currentPosition);
								} else if (!prevPressKeyEvent.ctrlKey && !event.ctrlKey) {
									window.prevScrollTop = $(window).scrollTop();
									var r = currentPosition.find('.reply');
									if(r.length>0){
										r.click();
									}
								}
								break;
							case 'T':
								if (prevPressKeyEvent.keyCode == 84 && !prevPressKeyEvent.shiftKey && !event.shiftKey){
									_screenname = currentPosition.find('.screen-name').text();
									Shortcut.retweetWithQuote(_screenname, currentPosition);
								}
								break;
							case 'O':
								if (!prevPressKeyEvent.shiftKey && !event.shiftKey){
									var t = currentPosition.find('span.entry-content');
									Translate.exec($(t[0]).text(),Setting.get('translate').translate_language, t);
								}
						}
						break;
					}

					return false;
			}).keydown(function(event){
				var _k = event.keyCode;
				var k = String.fromCharCode(event.keyCode);
				if((Setting.get('suggest').value && sugg.isActive()) || $('#status_login_box').hasClass('show'))
					return;
				if($(event.originalEvent.target).attr('id') == 'status'){
				} else {
					switch(event.originalEvent.target.type){
						case 'textarea':
						case 'text':
							return;
					}
					switch(k){
						case 'J':
						case 'K':
							if(currentPosition.length==0 || currentPosition[0].clientHeight == 0){
								window.currentPosition = $('#timeline li:eq(0)');
							}
							var c = k == 'J' ? currentPosition.next() : currentPosition.prev();
							if(c.length ==1) {
								$('.hentry').removeClass('focus');
								c.addClass('focus');
								currentPosition = c;
								var cs = $(window).scrollTop();
								scrollTo(0,currentPosition.position().top);
								if(cs == $(window).scrollTop() && !$('#pagination a').hasClass('loading')){
									$('#pagination a').click();
								}
							} else if(k == 'J' && !$('#pagination a').hasClass('loading'))
								$('#pagination a').click();
							break;
					}
				}
			})

		}
		Shortcut.replyAll = function(_screenname, hentry) {
			window.prevScrollTop = $(window).scrollTop();
			if(_screenname == '' && $('#profile_box').is(':visible')){
				_screenname = profile.user;
				profile.close();
			}
			var rs = $(hentry).find('.entry-content').text().match(/@\w+/g);
			rs = (rs==null ? [] : rs);
			for(var i = 0; i < rs.length; i++){
				if(rs[i] == '@'+user){
					rs.splice(i,1);
				}
			}
			rs.unshift('@'+_screenname);
			$('#status').val(rs.unique().join(' ')+' ').focus();
			if((target = $(hentry).attr('id').match(/status_(\d+)/)[1]) > 0){
				$('#in_reply_to_status_id').val(target);
				$('#in_reply_to').val(_screenname);
			}
		}
		Shortcut.retweetWithQuote = function(_screenname, hentry) {
			window.prevScrollTop = $(window).scrollTop();
			$('#status').focus();
			if(_screenname == '' && $('#profile_box').is(':visible')){
				_screenname = profile.user;
				profile.close();
			}
			$('#status').val('RT @'+_screenname+': '+$.trim($(hentry).find('.entry-content').text()));
		}
		Shortcut.init();
		Shortcut.toggle = function(){
			if($('#shortcut_help').hasClass('collapsed')){
				$('#shortcut_help').removeClass('collapsed');
				$('#shortcut').show();
				$.cookie('shortcut_'+user,'1',{expires:3650, path:'/'});
				Shortcut.show = true;
			} else {
				$('#shortcut_help').addClass('collapsed');
				$('#shortcut').hide();
				$.cookie('shortcut_'+user,'0',{expires:3650, path:'/'});
				Shortcut.show = false;
			}
		}
	}

	Shortcut();

	function Privacy(){
		Privacy.id = 0;
		Privacy.interval = Setting.get('privacy').privacy_interval*1000;
		Privacy.privacy_hide_dm = Setting.get('privacy').privacy_hide_dm;
		Privacy.privacy_hide_all = Setting.get('privacy').privacy_hide_all;
		Privacy.flag = false; //true : sleep
		Privacy.init = function(){
			$(window).mousemove(function(){Privacy.recheck();}).keydown(function(){Privacy.recheck();}).scroll(function(){Privacy.recheck();})
			Privacy.id = setInterval("Privacy.check()", Privacy.interval);
		}
		Privacy.getTarget = function(){
			var t = [];
			if(Privacy.privacy_hide_all) {
				return [$('body')];
			} else {
				if(Privacy.privacy_hide_dm){
					t.push($('.section.grid.DM, #inbox #content div.section'));
				}
			}
			return t;
		}
		Privacy.recheck = function(){
			clearInterval(Privacy.id);
			Privacy.id = setInterval("Privacy.check()", Privacy.interval);
			if(!Privacy.flag)
				return;
			var t = Privacy.getTarget();
			for(var i = 0; i < t.length; i++){
				t[i].css('visibility','');
			}
			Privacy.flag = false;
		}
		Privacy.check = function(){
		var t = Privacy.getTarget();
			for(var i = 0; i < t.length; i++){
				t[i].css('visibility','hidden');
			}
			Privacy.flag = true;
		}
		Privacy.init();
	}
	if(Setting.get('privacy').value){
		Privacy();
	}

	function FollowerList(){
		if(pageuser != undefined && user != pageuser){
			return;
		}
		FollowerList.show;
		FollowerList.isLoading = false;

		$('#FollowerList #fss_menu').live('click',function(){
			FollowerList.toggle();
		})
		FollowerList.open = function(){
			$('#FollowerList').removeClass('collapsed');
			$('#FollowerList #sidebar-menu').show();
			$('#followers_view_all').show();
			if(!FollowerList.isLoading)
				FollowerList.fetch();
			$.cookie('FollowerList_'+user,'1',{expires:3650, path:'/'});
			FollowerList.show = true;
		}
		FollowerList.close = function(){
			$('#FollowerList').addClass('collapsed');
			$('#FollowerList #sidebar-menu').hide();
			$('#followers_view_all').hide();
			$.cookie('FollowerList_'+user,'0',{expires:3650, path:'/'});
			FollowerList.show = false;
		}
		FollowerList.toggle = function(){
			if($('#FollowerList').hasClass('collapsed')){
				FollowerList.open();
			} else {
				FollowerList.close();
			}
		}

		FollowerList.fetch = function(nextpage){
			$('#grid_pagination.'+this.id+' a.round.more').addClass('loading').html('');
			var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
			req.open('GET', (nextpage==null || max_id==null) ? '/followers' : '://twitter.com/followers?page='+nextpage, true);
			req.setRequestHeader('Accept','application/json, text/javascript, */*');
			req.self= this;
			$('#FollowerList').addClass('loading');
			FollowerList.isLoading = true;
			req.onreadystatechange = function(){
				if (req.readyState == 4 && req.status == 200) {
					var html = this.responseText;
					var tr = html.match(/(<tr id="user_[\s\S]+?<\/tr>)/mg);
					for(var i = 0 ; i < tr.length; i ++){
						try{
							var e=tr[i];
							var screenname = fullname = img = '';
							try{screenname = e.match(/<a href="https?:\/\/twitter.com\/(.+?)".+?title="(.+?)">/)}catch(e){};
							try{fullname = e.match(/<span class="label fullname">(.+?)<\/span>/);}catch(e){};
							try{img = e.match(/<img .+?src="(.+?)"/);}catch(e){};
							var s = '<span class="vcard"><a title="'+fullname[1]+'" rel="contact" hreflang="en" class="url" href="/'+screenname[1]+'"><img width="24" height="24" src="'+img[1].replace(/normal/, 'mini')+'" class="photo fn" alt="'+fullname[1]+'"/></a></span>';
							$('#followers_list').append(s);
						} catch(e){
							//console.log(e);
						}
					}
					$('#FollowerList').removeClass('loading');
				}
			}
			req.send(null);
		}
		this.init = function(nest){
			if($.cookie('FollowerList_'+user) == null || $.cookie('FollowerList_'+user) == '0'){
				$.cookie('FollowerList_'+user,'0',{expires:3650, path:'/'});
				FollowerList.show = false;
			} else {
				$.cookie('FollowerList_'+user,'1',{expires:3650, path:'/'});
				FollowerList.show = true;
			}
			$('div#following').after('\
			<hr/><div class="collapsible'+(FollowerList.show ? '' : ' collapsed')+'" id="FollowerList">\
				<h2 id="fss_menu" class="sidebar-title"><span>Followers</span></h2>\
				<div class="sidebar-menu">\
					<div id="followers_list"></div>\
					<div id="followers_view_all" style="display:none"><a rel="me" href="/followers">View all…</a></div>\
				</div>\
			</div>');
			if(FollowerList.show){
				FollowerList.open();
			} else {
				FollowerList.close()
			}
		}
		this.init();
	}
	FollowerList();

	Notice = function(msg,rtmsg,msgnum,nextmsg){
		Notice.msg = msg;
		Notice.rtmsg = rtmsg;
		Notice.msgnum = msgnum;
		Notice.close = function(){
			$.cookie('notice'+Notice.msgnum,'checked', {expires:3650})
			$('.notice-body').remove();
		}
		Notice.init = function(){
			//$.cookie('notice'+Notice.msgnum)
			//if(true){
			if($.cookie('noticeDontShowMsg') != 'checked' && $.cookie('notice'+Notice.msgnum) != 'checked'){
				$('#monkeyFlySetting').after('<div class="notice-body"><div class="msg">'+Notice.msg+'</div><div class="control"><a class="a-btn a-btn-m retweet">RT</a><a class="a-btn a-btn-m close">close</a><a class="a-btn a-btn-m dontshowmsg">Don\'t show messages</a></div><img class="direction" src=""></div>');
			}
			$('.notice-body .control .retweet').click(function(){
				$('#status').val(Notice.rtmsg);
				$('textarea#status, textarea#text').css('height', '90px');
				$('div.bar,#currently,#tweeting_controls,div#update_notifications').show();
				if(nextmsg){
					(new InfoNotification()).setMessage(_(nextmsg)).show();
				}
				Notice.close();
			})
			$('.notice-body .control .close').click(function(){
				Notice.close();
			})
			$('.notice-body .control .dontshowmsg').click(function(){
				$.cookie('noticeDontShowMsg','checked', {expires:3650})
				Notice.close();
			})
		}
		Notice.init();
	}
	//Translation function was added in #monkeyfly
	/*
	Notice('<span style="font-weight:bold">MonkeyFly New</span><br/>Now you can use MonkeyFly by the Safari Extension.<br /><a href="http://monkeyfly.egoing.net" target="_blank">http://monkeyfly.egoing.net</a>', "RT @graphittie Now you can use MonkeyFly by the Safari Extension. http://monkeyfly.egoing.net", 13, null);
	*/
	//'Next feature:<span style="color:red">Skin Community</span> OR  <span style="color:red">Isolate Panel</span>. Thank you for RT!'

	$('.hentry').livequery('click',function(){
		currentPosition = $(this);
		$('.hentry').removeClass('focus');
		currentPosition.addClass('focus');
	});

	var hideFlag = false;
	$('head').append('<style type="text/css">div.bar,#currently,#tweeting_controls,div#update_notifications,textarea#status,textarea#text{height:30px;font-size:13px;}#tweeting_controls,#update_notifications, #status_update_box div.bar{display:none;}</style>');
	$('textarea#status, textarea#text').each(function(){
			if(this.value != ''){
				$('textarea#status, textarea#text').css('height', '90px');
				$('div.bar,#currently,#tweeting_controls,#update_notifications,#status_update_box div.bar').show();
				hideFlag = true
			}
	})
	if(!hideFlag) {
		$('textarea#status, textarea#text').focus(function(){
			$('textarea#status, textarea#text').css('height', '90px');
			$('div.bar,#currently,#tweeting_controls,#update_notifications,#status_update_box div.bar').show();
		})
		$('textarea#status, textarea#text').blur();
	}
	focus(document.body)
	
	if (Setting.get('profile').value) {
		$(document).ready(function() {
			$('a.detail-btn').live('click', function(event) {
				twttr.HOVERCARD.hide();
			
				if (profile.profile.is(':visible'))
					profile.close();
			
				profile.user = $(this).parents('div.hovercard-content-inner').find('a.screen_name:first').text().replace('@', '');
				profile.open();
			
				event.preventDefault();
			});
	
			if (twttr.HOVERCARD) {
				$.get("/mustaches/hovercard_content.html", null, function (D) {
					twttr.templates.hovercard_content = D.replace(/<div class="(follow-controls|is-you)">([^\$]+?)<\/div>/gm, '<div class="$1">$2</div><a class="a-btn detail-btn" href="#">Detail</a>');
				}, "html");
			} else {
				//if (page.locale == 'ja') {
					$.getScript('http://a2.twimg.com/a/1274899949/javascripts/controls.js', function() {
						$.getScript('http://a3.twimg.com/a/1274899949/javascripts/hover_cards.js', function() {
							twttr.HOVERCARD = new twttr.HoverCard('#timeline img.photo.fn:not(.shared-by-avatar-tiles img.photo.fn), #timeline .entry-content a.tweet-url.username, .retweet-meta a.screen-name');

							// this screen name next to the avatar triggers the hovercard ON the avatar
							$('#timeline a.tweet-url.screen-name').live("mouseover", function() {
								$(this).closest('li').find('img.photo.fn:not(.shared-by-avatar-tiles img.photo.fn)').trigger('mouseover');
							}).live("mouseout", function() {
								$(this).closest('li').find('img.photo.fn:not(.shared-by-avatar-tiles img.photo.fn)').trigger('mouseout');
							});

							$('ul.sidebar-menu a').bind('click', function(e) {
								var $this = $(this).parent();
								if ($this.is('#primary_nav li, ul.lists-links li')) {
									twttr.HOVERCARD.enable();
								} else {
									twttr.HOVERCARD.disable();
								}
							});

							$('#content li.status').live('mousedown', function() {
								twttr.HOVERCARD.unregister();
							});

							$('body').bind('mouseup', function() {
								twttr.HOVERCARD.register();
							});
						})
					});
				//}
				twttr.loadTemplate = function (A, B) {
					if (twttr.templates[A]) {
						return twttr.templates[A]
					}
					B = B ||
					function () {};
					$.get("/mustaches/" + A + ".html", null, function (D) {
						var C = {
							templates: {}
						};
	
						if (A == 'hovercard_content') {
							D = D.replace(/<div class="(follow-controls|is-you)">([^\$]+?)<\/div>/gm, '<div class="$1">$2</div><a class="a-btn detail-btn" href="#">Detail</a>');
						}
	
						C.templates[A] = D;
						twttr.merge(twttr, C, true);
						B(twttr.templates)
					}, "html")
				};
			}
		});
	}
	
	function processTimelineRefresh(J, D) {
		if (twttr.is.def(J.users)) {
			twttr.User.merge(J.users)
		}
		var G = $("#new_results_notification").meta().timeline;
		var K = $("<div>" + J["#timeline"] + "</div>");
		var A = $("#content #grid_layout_0 ol#timeline");
		if(!A.length)
			var A = $("ol#timeline")
		K.find("#timeline > li").each(function () {
			if (A.find("li#" + this.id).length) {
				$(this).remove()
			}
		});
		var F = K.find("ol > li");
		var C = F.length;
		var E = ($("#new_results_notification").data("count") || 0) + C;
		if (C) {
			A.prepend(F.addClass("buffered"));
			K.remove();
			A.find("li.buffered:gt(" + (G.max_refresh_size - 1) + ")").remove();
			var B = {
				results_count: numberWithDelimiter(E),
				username: user//getCurrentUserScreenName()
			};
			var H = $("#results_update").is(":visible") ? "" : ' style="display:none;"';
			var I = '<a id="results_update" class="minor-notification" href="/' + D + '" accesskey="n"' + H + ">";
			if (D == "inbox") {
				I += ((E == 1) ? _("1 new message.") : _("%{results_count} new messages.", B))
			} else {
				if (D == "replies") {
					I += ((E == 1) ? _("1 new mention of @%{username}.", B) : _("%{results_count} new mentions of @%{username}.", B))
				} else {
					I += ((E == 1) ? _("1 new tweet.") : _("%{results_count} new tweets.", B))
				}
			}
			I += "</a>";
			$("#results_update").replaceWith(I);
			$("#results_update").click(function () {
				$("#content ol#timeline > li.buffered").addClass("unbuffered").removeClass("buffered");
				if ($("#new_results_notification").data("count") > G.max_refresh_size) {
					$("#content ol#timeline > li:not(.unbuffered)").remove();
					var M = $("#content ol#timeline > li").attr("id").replace(/^[^0-9]+/, "");
					var L = ($("#results_update").attr("href") || window.location.hash || D).replace(/^([^\/])/, "/$1") + "?max_id=" + M + "&page=3&twttr=true";
					$("#pagination").html('<div id="#pagination"><a id="more" class="round more" rel="next" href="' + L + '">' + _("more") + "</a></div>")
				} else {
					$("#content ol#timeline > li.last-on-refresh").removeClass("last-on-refresh");
					$("#content ol#timeline > li.unbuffered:last").addClass("last-on-refresh")
				}
				updateTimeAgo();
				$("#content ol#timeline > li.unbuffered").removeClass("unbuffered");
				$("#results_update").hide();
				addCountToDocumentTitle();
				$.Timeline.triggerPageHeightChangedEvent();
				$("#new_results_notification").data("count", 0);
				return false
			});
			$("#new_results_notification").data("count", E);
			$("#results_update:hidden").slideDown("normal", function () {
				$.Timeline.triggerPageHeightChangedEvent();
				var L = $(this);
				if (twttr.is.def(twttr.HOVERCARD)) {
					twttr.HOVERCARD.reposition(L.get(0).offsetHeight + parseInt(L.css("margin-top")))
				}
			});
			addCountToDocumentTitle(E)
		} else {
			K.remove()
		}
		page.newResults = (C > 0)
	}
	
	text2Tweet = function(content){
		content = content.replace(/@(\w+)/g,'<a href="/$1" class="tweet-url username">@$1</a>');
		content = content.replace(/#(\w+)/g,'<a class="tweet-url hashtag" title="#$1" href="/search?q=%23$1">#$1</a>');
		content = content.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,"<a href=\"$1\" target=\"_blank\">$1</a>");
		return content;	
	}
	
	Translate();
}

$('body').trigger('monkeyfly');